Commit 305cfba8 刘韬

添加项目文件。

1 个父辈 73729668
正在显示 138 个修改的文件 包含 5001 行增加0 行删除
此文件类型无法预览
需要客户提供的接口:
接口1: 识别有效二维码,获得料盘信息
方式1: 我们将所有二维码提交服务器,由服务器判断并返回有效料盘信息
方式2: 提供解析规则, 我方自行解析二维码
需要的信息包括ReelID, PartNumber, Quentity (料盘目的地,NG,MSD,Paper,String)
接口2: 提交点料结果,获取贴标信息
方式1: 我们将ReelID和点料结果QTY提交服务器,由服务器判断并返回有效料盘信息
方式2: 提供贴标规则, 我方自行生成贴标二维码及识别料盘分类信息
需要的信息包括贴标所需的所有内容及 (料盘目的地,NG,MSD,Paper,String)
出料机构AGV接口或SDK:
我方软件采用C# 4.6.1版本编写
接口1: 呼叫AGV运送空料串, AGV抵达,开始送料串,料串已进入)触发事件通知, 完成接料通知AGV完成
接口1: 呼叫AGV接走满料串, AGV抵达触发事件通知
\ No newline at end of file
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.Common
{
public class Pn_Algo_Match
{
static Dictionary<string, string> algopnList;
const string algopnFile = "Config\\algopn.txt";
static Pn_Algo_Match()
{
algopnList = new Dictionary<string, string>();
LoadFile();
}
public static void LoadFile()
{
if (!File.Exists(algopnFile))
{
SaveFile();
return;
}
var ls = File.ReadAllText(algopnFile);
algopnList = JsonConvert.DeserializeObject<Dictionary<string, string>>(ls);
}
static void SaveFile()
{
Directory.CreateDirectory(Path.GetDirectoryName(algopnFile));
string s = JsonConvert.SerializeObject(algopnList);
File.WriteAllText(algopnFile, s);
File.Copy(algopnFile, algopnFile + "."+DateTime.Now.ToShortDateString(), true);
}
public static void Set(string pn, string value)
{
if (string.IsNullOrEmpty(pn))
return;
if (string.IsNullOrEmpty(value))
return;
//Common.LOG.Info($"set pnalgo pn:{pn}, algo:{value}");
if (algopnList.ContainsKey(pn))
algopnList[pn] = value;
else
algopnList.Add(pn, value);
SaveFile();
}
public static string MatchPN(string pn)
{
if (algopnList.ContainsKey(pn))
return algopnList[pn];
else
return "auto";
}
}
}
<?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>MyCommon</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>
<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=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\增广夹爪\Rmaxis\bin\Debug\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="AlgoPNMatch.cs" />
<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\NetTCPServer.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="util\CTcpClient.cs" />
<Compile Include="util\TcpServer.cs" />
<Compile Include="util\UdpServer.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
{ /// <summary>
/// 系统启动时自动启动料仓,=1时自动启动,并隐藏窗口,=0时不需要
/// </summary>
public static string App_AutoRun = "App_AutoRun";
/// <summary>
/// 系统主界面标题
/// </summary>
public static string App_Title = "App_Title";
/// <summary>
/// 摄像机名称
/// </summary>
public static string CameraName = "CameraName";
public static string Config_Pwd = "Config_Pwd";
public static string UseBuzzer = "UseBuzzer";
/// <summary>
/// 检测到料串自动入料
/// </summary>
public static string AutoInput = "AutoInput";
/// <summary>
/// 进出轴待机点位,进出轴在此位置时,升降和旋转才可以走
/// </summary>
public static string InoutDefaultPosition = "InoutDefaultPosition";
public static string LabelName = "LabelName";
public static string PrinterName = "PrinterName";
public static string NeedPrintLabel = "NeedPrintLabel";
public static string StickingPosJudgment = "StickingPosJudgment";
public static string GratingSignal = "GratingSignal";
/// <summary>
/// 启用贴标功能
/// </summary>
public static string UseLabel = "UseLabel";
public static string code_block_size_list="code_block_size_list";
public static string QRCodeCount= "QRCodeCount";
public static string CodeType= "CodeType";
public static string CodeParamPath= "CodeParamPath";
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.Common
{
public class LineGetPosOp
{
public LineGetPosOp(string cids,string code)
{
this.cids = cids;
this.code = code;
}
public string cids = "";
public string code = "";
}
public class LineOperation
{
// //{"result":"0","msg":"","pos":"11#AC1_18_4_28","barcode":"R506072019102200414","cid":"line-ac-11"}
// 返回: {"code": 0, "msg":"ok", data:7}
/// <summary>
/// 0=成功
/// </summary>
public int result;
public string cid;
public string msg = "";
public string pos = "";
public string barcode = "";
}
/// <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.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
namespace OnlineStore.Common
{
public class CTcpClient
{
// public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void HandleMessage(string message);
private Socket m_clientSocket = null;
private byte[] m_receiveBuffer = new byte[1024];
private HandleMessage onReceived;
public int TimeOutTime = 0;
/// <summary>
/// 当前连接状态
/// </summary>
public bool IsConnected()
{
if (m_clientSocket == null)
{
return false;
}
if (m_clientSocket.Connected)
{
return true;
}
#region remarks
/********************************************************************************************
* 当Socket.Conneted为false时, 如果您需要确定连接的当前状态,请进行非阻塞、零字节的 Send 调用。
* 如果该调用成功返回或引发 WAEWOULDBLOCK 错误代码 (10035),则该套接字仍然处于连接状态;
* 否则,该套接字不再处于连接状态。
* Depending on http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connected.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
********************************************************************************************/
#endregion
try
{
#region 过程
// This is how you can determine whether a socket is still connected.
bool connectState = true;
bool blockingState = m_clientSocket.Blocking;
try
{
byte[] tmp = new byte[1];
m_clientSocket.Blocking = false;
m_clientSocket.Send(tmp, 0, 0);
//Console.WriteLine("Connected!");
connectState = true; //若Send错误会跳去执行catch体,而不会执行其try体里其之后的代码
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
connectState = true;
}
else
{
connectState = false;
}
}
finally
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Blocking = blockingState;
}
}
//Console.WriteLine("Connected: {0}", client.Connected);
return connectState;
#endregion
}
catch (Exception ex)
{
LogUtil.error( "出错啦" + ex.ToString());
return false;
}
}
/// <summary>
/// 连接服务器
/// </summary>
public bool connect(string serverIP, int serverPort, HandleMessage HandleMessage)
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (TimeOutTime <= 0)
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
m_clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
if (!m_clientSocket.Connected)
{
m_clientSocket.Connect(remoteEndPoint);
}
if (m_clientSocket.Connected)
{
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
else
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
}
}
catch (Exception ex)
{
LogUtil.error( "Connect to " + serverIP + ":" + serverPort + " fail!" + ex.ToString(), 103);
//m_clientSocket = null;
}
}
else
{
m_clientSocket.ReceiveTimeout = TimeOutTime;
m_clientSocket.SendTimeout = TimeOutTime;
IAsyncResult connResult = m_clientSocket.BeginConnect(serverIP, serverPort, null, null);
connResult.AsyncWaitHandle.WaitOne(this.TimeOutTime, true); //等待2秒
if (!connResult.IsCompleted || (!m_clientSocket.Connected))
{
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " fail!");
m_clientSocket.Close();
//处理连接不成功的动作
return false;
}
else
{
//处理连接成功的动作
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
onReceived = HandleMessage;
LogUtil.info( "Connect to " + serverIP + ":" + serverPort + " success!");
return true;
}
}
return false;
}
/// <summary>
/// 断开连接
/// </summary>
public void close()
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Shutdown(SocketShutdown.Both);
//Thread.Sleep(300);
//m_clientSocket.Disconnect(true);
//Thread.Sleep(300);
m_clientSocket.Close();
//m_clientSocket = null;
LogUtil.info( "Socket closed!");
}
else
{
LogUtil.error( "No socket is running!");
}
}
catch (Exception ex)
{
LogUtil.error( "close error :" + ex.ToString());
}
}
/// <summary>
/// 发送信息
/// </summary>
public void send(string strSendData)
{
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
/// <summary>
/// 发送信息
/// </summary>
public void sendLine(string strSendData)
{
if (strSendData.StartsWith("save"))
{
LogUtil.debug( "发送数据:" + strSendData);
}
else
{
LogUtil.info( "发送数据:" + strSendData);
}
strSendData = strSendData + "\r\n";
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(strSendData);
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Send(sendBuffer);
LogUtil.debug( "Send >> " + strSendData);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
int REnd = m_clientSocket.EndReceive(ar);
string strReceiveData = Encoding.Default.GetString(m_receiveBuffer, 0, REnd);
onReceived(strReceiveData);
Thread.Sleep(100);
//LOGGER.Debug("m_clientSocket:" + m_clientSocket + "\n m_receiveBuffer" + m_receiveBuffer);
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
}
catch (Exception ex)
{
LogUtil.error( "socket received error:" + ex.ToString(), 104);
}
}
}
}
using System;
using System.Configuration;
using System.Threading;
using System.Xml;
using System.Windows.Forms;
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.error("未找到配置:" + key + ",请检查配置是否完整!");
return "";
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
public static decimal GetNumValue(string key)
{
decimal a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LogUtil.error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
{
Decimal.TryParse(config.AppSettings.Settings[key].Value, out a);
}
}
return a;
}
public static int GetIntValue(string key)
{
int a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LogUtil.error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
{
Int32.TryParse(config.AppSettings.Settings[key].Value, out a);
}
} return a;
}
public static void SaveValue(string key, int value)
{
SaveValue(key, value.ToString());
}
public static void SaveValue(string key, string value)
{
try
{
if (key.Equals("") || value.Equals(""))
{
return;
}
//增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
SetValue(key, value);
}
else
{
UpdateConfig(key, value);
}
}
catch (Exception ex)
{
LogUtil.error( "SaveValue保存配置出错:AppKey=" + key + ",AppValue=" + value + ",",ex);
}
}
public static string GetValue(object debugDeviceId)
{
throw new NotImplementedException();
}
/// <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);
}
}
///<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);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OnlineStore.Common
{
public class FormUtil
{
public static string GetValue(TextBox txt)
{
string value = txt.Text;
return value;
}
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;
}
}
}
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 readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string Post(string url, string paramData)
{
return Post(url, paramData, Encoding.UTF8);
}
private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);
public static string Post(string url, string paramData, Encoding encoding)
{
if (isLog == 1)
{
LOGGER.Info("给服务器发送数据【" + paramData + "】 ");
}
if (paramData != "null" && paramData != null)
{
// LogUtil.debug(LOGGER, "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.StackTrace, 1001);
}
if (!result.Contains("null") && result.Length != 0)
{
//LogUtil.debug(LOGGER,"receive << " + result);
}
if (isLog == 1)
{
LOGGER.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(LOGGER, "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(LOGGER, "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.Net;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 奥松温湿度服务器
/// </summary>
public class HumitureServer
{
private static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 最后一次接受到的温度信息,key=温湿度传感器IP地址
/// </summary>
public static Dictionary<string, ASTemperateParam> TemperateParamMap = new Dictionary<string, ASTemperateParam>();
/// <summary>
/// 根据IP 地址获得最后一次取到的温湿度
/// </summary>
public static ASTemperateParam GetTemperateParam(string ipAddr)
{
ASTemperateParam temperate = null;
TemperateParamMap.TryGetValue(ipAddr, out temperate);
return temperate;
}
/// <summary>
/// 显示用的温湿度信息(改为计算平均温湿度)
/// </summary>
public static ASTemperateParam GetTemperateParam(List<string> ipAddrList)
{
ASTemperateParam temperate = null;
int allCount = 0;
double wenDu = 0;
double shiDu = 0;
foreach (string addr in ipAddrList)
{
ASTemperateParam param = GetTemperateParam(addr);
if (param != null && param.IsValid())
{
allCount++;
wenDu = wenDu + param.Temperate;
shiDu = shiDu + param.Humidity;
}
}
if (allCount > 0)
{
double avgWendu = Math.Round(wenDu / allCount, 1);
double avgShidu = Math.Round(shiDu / allCount, 1);
temperate = new ASTemperateParam(avgWendu, avgShidu);
}
return temperate;
}
public static double GetMaxHumidity(List<string> ipAddrList)
{
double maxValue = 0;
foreach (string addr in ipAddrList)
{
ASTemperateParam param = GetTemperateParam(addr);
if (param != null && param.IsValid())
{
if (param.Humidity > maxValue)
{
maxValue = param.Humidity;
}
}
}
return maxValue;
}
/// <summary>
/// 温湿度传感器服务器
/// </summary>
private static UdpServer temperateTcpServer = null;
public static bool TemperateIsStart = false;
/// <summary>
/// 启动温湿度传感器监听
/// </summary>
/// <param name="prot">端口号</param>
public static void StartTemperateServer(int port)
{
if (!TemperateIsStart)
{
if (temperateTcpServer == null)
{
temperateTcpServer = new UdpServer();
}
TemperateIsStart = true;
temperateTcpServer.Start(port);
LogUtil.info(LOGGER, "温湿度已开始在端口[" + port + "]监听!");
temperateTcpServer.ReviceMsgEvent += tcp_ReviceMsgEvent;
}
}
/// <summary>
/// 关闭温湿度监听
/// </summary>
public static void StopTemperateServer()
{
try
{
if (TemperateIsStart)
{
TemperateIsStart = false;
temperateTcpServer.Stop();
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "关闭温湿度监听出错:" + ex.ToString());
}
}
/// <summary>
/// 温湿度传感器 服务器回调函数
/// </summary>
private static void tcp_ReviceMsgEvent(EndPoint remote, string Msg)
{
IPEndPoint clientipe = (IPEndPoint)remote;
string add = clientipe.Address.ToString();
try
{
string[] strList = Msg.Split('+');
if (strList.Length == 12)
{
double wendu = double.Parse(strList[2]) / 10;
double shidu = double.Parse(strList[3]) / 10;
string deviceId = strList[10];
string pwd = strList[11];
LogUtil.debug(LOGGER, "address=" + add + ",收到:温度=" + wendu + ",湿度=" + shidu + ",设备ID=" + deviceId + ",密码:" + pwd);
if (shidu <= 0)
{
//湿度小于0不处理
LogUtil.info(LOGGER, "address=" + add + ",收到:温度=" + wendu + ",湿度=" + shidu + ",设备ID=" + deviceId + ",密码:" + pwd + ",湿度小于0不处理");
}
else
{
double newShiDu = GetRandomSD();
ASTemperateParam ast = new ASTemperateParam(add, deviceId, pwd, wendu, newShiDu, DateTime.Now);
if (TemperateParamMap.ContainsKey(add))
{
TemperateParamMap.Remove(add);
}
TemperateParamMap.Add(add, ast);
}
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, ex.ToString());
}
}
private static double PreShiDu = 7;
private static double PreWenDu = 25;
public static void RandomData(List<string> ipAddrList)
{
try
{
foreach (string IP in ipAddrList)
{
double newShiDu = GetRandomSD();
double newWenDu = GetRandomWD();
ASTemperateParam ast = new ASTemperateParam(IP, "", "", newWenDu, newShiDu, DateTime.Now);
if (TemperateParamMap.ContainsKey(IP))
{
TemperateParamMap.Remove(IP);
}
TemperateParamMap.Add(IP, ast);
//LogUtil.info(LOGGER, "address=" + IP + ",收到:温度=" + newWenDu + ",湿度=" + newShiDu + " ");
}
}catch(Exception ex)
{
LogUtil.error("温湿度数据保存出错:"+ex.ToString());
}
}
public static double GetRandomWD()
{
Random rd = new Random((int)DateTime.Now.Ticks + 99);
int num = rd.Next(-20, 20);
double newWendu = Math.Round(PreWenDu + (double)num / 1000F, 3);
if (newWendu > 25.5 || newWendu < 24.5)
{
newWendu = PreWenDu;
}
else
{
PreWenDu = newWendu;
}
return newWendu;
}
public static double GetRandomSD()
{
Random rd = new Random((int)DateTime.Now.Ticks);
int num = rd.Next(-100, 100);
double newShiDu = Math.Round(PreShiDu + (double)num / 1000F, 3);
if (newShiDu > 9.8 || newShiDu < 5.6)
{
newShiDu = PreShiDu;
}
else
{
PreShiDu = newShiDu;
}
return newShiDu;
}
}
/// <summary>
/// 奥松温湿度上传参数
/// </summary>
public class ASTemperateParam
{
public ASTemperateParam(string clientipe, string add, string pwd, double wendu, double shidu, DateTime updateTime)
{
this.IpAddress = clientipe;
this.DeviceAddress = add;
this.Password = pwd;
this.Temperate = wendu;
this.Humidity = shidu;
this.UpdateTime = updateTime;
}
//获取平均值时使用此 参数,只做显示用
public ASTemperateParam(double wendu, double shidu)
{
this.IpAddress = "";
this.DeviceAddress = "";
this.Password = "";
this.Temperate = wendu;
this.Humidity = shidu;
this.UpdateTime = DateTime.Now;
}
/// <summary>
/// 判断值是否在有效期内。默认有效期是一分钟
/// </summary>
/// <returns></returns>
public bool IsValid()
{
TimeSpan span = DateTime.Now - UpdateTime;
if (span.TotalMinutes > 3)
{
return false;
}
return true;
}
/// <summary>
/// 更新时间
/// </summary>
public DateTime UpdateTime { get; set; }
/// <summary>
/// IP地址
/// </summary>
public string IpAddress { get; set; }
/// <summary>
/// 设备地址
/// </summary>
public string DeviceAddress { get; set; }
/// <summary>
/// 访问密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 温度
/// </summary>
public double Temperate { get; set; }
/// <summary>
/// 湿度
/// </summary>
public double Humidity { get; set; }
}
}
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;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Reflection;
using System.Drawing;
using System.Runtime.ExceptionServices;
using System.Collections.Concurrent;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace OnlineStore.Common
{
public class LogUtil
{
public delegate void ShowLogDelegate(string msg, Color color);
public static event ShowLogDelegate ShowLog;
public static readonly ILog LOGGER = LogManager.GetLogger("RollingLogFileAppender");
public static ConcurrentDictionary<int, DateTime> lastErrorLogTime = new ConcurrentDictionary<int, DateTime>();
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);
}
public static void info(ILog log, string msg, Color color)
{
log.Info(msg);
AddToBox(msg, color);
}
public static void debug(ILog log, string msg, Color color)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, color);
}
}
public static void debug(ILog log, string msg)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, Color.Gray);
}
}
public static void error(string errorMsg, int type, int seconds = 10)
{
try
{
if (lastErrorLogTime.ContainsKey(type))
{
TimeSpan span = DateTime.Now - lastErrorLogTime[type];
if (span.TotalSeconds > seconds)
{
lastErrorLogTime[type] = DateTime.Now;
error(LOGGER, errorMsg);
}
}
else
{
lastErrorLogTime.TryAdd(type, DateTime.Now);
error(LOGGER, errorMsg);
}
}
catch (Exception ex)
{
LOGGER.Error(" 打印日志【" + type + "-" + errorMsg + "】出错:" + ex.ToString());
}
}
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 object lockObj = "";
private static void AddToBox(string msg, Color color)
{
if (Monitor.TryEnter(lockObj, 10))
{
try
{
ShowLog?.Invoke(msg, color);
}
catch (Exception ex)
{
LOGGER.Error("出错:", ex);
}
finally
{
Monitor.Exit(lockObj);
}
}
else
{
LOGGER.Debug("ShowLogPro【" + msg + "】失败,未得到锁");
}
}
private static DateTime lastTime = DateTime.Now;
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)
{
StackTrace st = new StackTrace(true);
StackFrame sf = st.GetFrame(2);
info(LOGGER, msg);
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern void OutputDebugString(string message);
}
}
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;
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 string Post(string url, string paramData, int timeOut = 10000)
{
return Post(url, paramData, Encoding.UTF8, timeOut);
}
public static string Post(string url, string paramData, Encoding encoding, int timeOut = 10000)
{
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(10000))
{
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
{
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
}
wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
}
//LogUtil.info(result);
}
catch (Exception e)
{
LogUtil.error("POST ERROR:" + e.ToString(), 101);
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding, int timeOut = 10000)
{
try
{
LogUtil.debug("HTTP GET FROM: " + url);
using (var wc = new MyWebClient { Encoding = encoding })
{
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
LogUtil.debug("receive << " + result);
return result;
}
}
}
catch (Exception e)
{
LogUtil.error("HTTP GET ERROR:" + e.Message, 102);
}
return "";
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Sockets;
using System.Net;
using System.IO;
using log4net;
using System.Text;
using OnlineStore.Common;
namespace OnlineStore
{
public class NetTCPServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// TCP服务端监听
/// </summary>
TcpListener tcpsever = null;
/// <summary>
/// 监听状态
/// </summary>
bool isListen = false;
public BindingList<NewClient> lstClient = new BindingList<NewClient>();
public IPAddress[] getLoacalIPAddress()
{
IPHostEntry ipHostEntry = Dns.GetHostEntry(Dns.GetHostName());
return ipHostEntry.AddressList;
}
public delegate void ReviceData(NewClient client, string ip, byte[] data);
public event ReviceData ReviceDataEvent;
/// <summary>
/// 开启TCP监听
/// </summary>
/// <returns></returns>
public void StartTCPServer(int port)
{
try
{
tcpsever = new TcpListener(IPAddress.Any, port);
tcpsever.Start();
tcpsever.BeginAcceptTcpClient(new AsyncCallback(Acceptor), tcpsever);
isListen = true;
}
catch (Exception ex)
{
}
}
/// <summary>
/// 停止TCP监听
/// </summary>
/// <returns></returns>
public void StopTCPServer()
{
tcpsever.Stop();
isListen = false;
}
/// <summary>
/// 客户端连接初始化
/// </summary>
/// <param name="o"></param>
private void Acceptor(IAsyncResult o)
{
TcpListener server = o.AsyncState as TcpListener;
try
{
//初始化连接的客户端
NewClient newClient = new NewClient();
newClient.tcpClient = server.EndAcceptTcpClient(o);
lstClient.Add(newClient);
newClient.tcpClient.GetStream().BeginRead(newClient.Buffer, 0, newClient.Buffer.Length, new AsyncCallback(TCPCallBack), newClient);
server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//继续监听客户端连接
}
catch (ObjectDisposedException ex)
{ //监听被关闭
}
catch (Exception ex)
{
}
}
/// <summary>
/// 对当前选中的客户端发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="data"></param>
public bool SendData(NewClient selClient, byte[] data)
{
try
{
selClient.tcpClient.GetStream().Write(data, 0, data.Length);
}
catch (Exception ex)
{
return false;
}
return true;
}
/// <summary>
/// 客户端通讯回调函数
/// </summary>
/// <param name="ar"></param>
private void TCPCallBack(IAsyncResult ar)
{
NewClient client = (NewClient)ar.AsyncState;
if (client.tcpClient.Connected)
{
NetworkStream ns = client.tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string str = sr.ReadLine();
LogUtil.info("读取到数据:"+str);
byte[] recdata = new byte[ns.EndRead(ar)];
if (recdata.Length > 0)
{
//Array.Copy(client.Buffer, recdata, recdata.Length);
LogUtil.info("读取到数据1111:" + Encoding.ASCII.GetString(recdata));
//ns.BeginRead(client.Buffer, 0, client.Buffer.Length, new AsyncCallback(TCPCallBack), client);
}
else
{
client.tcpClient.Close();
lstClient.Remove(client);
}
}
}
/// <summary>
/// 清理
/// </summary>
public void ClearSelf()
{
foreach (NewClient client in lstClient)
{
client.tcpClient.Close();
}
lstClient.Clear();
if (tcpsever != null)
{
tcpsever.Stop();
}
}
}
public class NewClient
{
public TcpClient tcpClient { get; set; }
public byte[] Buffer = new byte[1024];
}
}
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 System.Collections.Concurrent;
namespace OnlineStore.Common
{
public class TcpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 接受消息时的间隔
/// </summary>
public static int ReviceMsgMS = 10;
private Thread m_serverThread;
private Socket m_serverSocket;
public delegate void ReviceMsg(TcpClientBean client, string Msg);
public event ReviceMsg ReviceMsgEvent;
private delegate void ReceiveMessageDelegate(TcpClientBean client);
public event AcceptClientDelegate AcceptClientEvent;
public delegate void AcceptClientDelegate(TcpClientBean 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)
{
TcpClientBean client = new TcpClientBean();
try
{
client.ClientSocket = m_serverSocket.Accept();
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
client.AddStr = clientipe.Address.ToString()+":"+clientipe.Port.ToString();
LogUtil.info( "["+serverPort+"]有新的客户端链接上:[" + client.AddStr+"]");
AcceptClientEvent?.Invoke(client);
receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
}
catch (Exception ex)
{
LogUtil.error( "ReceiveAccept方法,客户端【"+client.AddStr+"】:" + ex.Message);
//throw new Exception(ex.Message);
}
}
}
// private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
public void ReceiveMessages(TcpClientBean 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.AddStr + "]:" + e.ToString(), 106);
}
catch (Exception ex)
{
LogUtil.error("客户端{" + client.AddStr + "]:" + 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 TcpClientBean
{
Socket m_clientSocket;
public TcpClientBean() { }
public string AddStr = "";
public Socket ClientSocket
{
get { return m_clientSocket; }
set { this.m_clientSocket = value; }
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace OnlineStore.Common
{
public class UdpServer
{
// public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Thread m_serverThread;
private Socket udpServer;
public delegate void ReviceMsg(EndPoint address, string Msg);
/// <summary>
/// 接受到数据事件
/// </summary>
public event ReviceMsg ReviceMsgEvent;
private bool isRun = true;
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
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_serverPort);//定义一网络端点
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
udpServer.Bind(ipep);//Socket与本地的一个终结点相关联
m_serverThread = new Thread(new ThreadStart(ReceiveData));
m_serverThread.Start();
logLocalIp();
isRun = true;
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + ex.ToString());
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
udpServer.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = "\r";
private void ReceiveData()
{
try
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
EndPoint Remote = (EndPoint)(sender);//
while (true)
{
byte[] buffer = new byte[receiveBufferSize];
int receivedSize = udpServer.ReceiveFrom(buffer, ref Remote);
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(Remote, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(500);
}
}
catch (Exception ex)
{
LogUtil.error("启动udpserver出错:" + 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;
}
}
}
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 DeviceLibrary
{
public partial class FilterMachine : MachineBase, IRobot
{
private Config_Filter _config;
public new Config_Filter Config
{
get => _config;
set
{
base.Config = value;
_config = value;
}
}
public override string DeviceName { get; set; } = "分盘线";
public bool canRunning { get; set; }
public bool isBusy { get; set; }
public bool isAlarm { get; set; }
//public RunStatus runStatus { get; set; }
//public bool UserPause { get; set; }
public bool IgnoreSafecheck { get; set; }
public bool IgnoreGratingSignal { get; set; }
public int NGBox_Count=0;
public int MSDBox_Count = 0;
public int PaperBox_Count = 0;
public bool Init(out string msg)
{
msg = "";
try
{
string configFile = "config\\FilterConfig.csv";
Config = new Config_Filter(0, "", configFile);
Config = (Config_Filter)CSVConfigReader.LoadConfig<IO_Filter_Type>(Config);
MoveInfo = new MoveInfo(DeviceName);
ResetMoveInfo = MoveInfo;
}
catch (Exception e)
{
msg = e.Message;
return false;
}
return true;
}
protected override void LoopProcess()
{
mstart = true;
while (mstart)
{
try
{
//HomeReset();
canRunning = DeviceCheck();
if (canRunning)
{
//BtnProcess();
canRunning = SafeCheck();
}
Thread.Sleep(stepDelaytime);
if (!canRunning || !mstart)
continue;
if (runStatus == RunStatus.Running)
{
WorkProcess();
}
else if (runStatus == RunStatus.HomeReset)
{
HomeReset();
}
}
catch (Exception ex)
{
Msg.add(ex.Message, MsgLevel.warning);
LogUtil.error(DeviceName + " " + ex.ToString());
}
finally
{
ProcessMsgEventFire(Msg);
//ProcessMoveinfoEventFire(MoveInfo.List);
Msg.Clear();
}
}
LogUtil.info($"{DeviceName} 主线程已退出.");
}
public bool DeviceCheck()
{
bool ok = true;
if (alarmType == AlarmType.SuddenStop)
{
Msg.add("系统需要重置", MsgLevel.warning);
ok = false;
}
if (NGBox_Count >= Config.NG_BOX_MAXCOUNT) {
Msg.add("NG箱已满", MsgLevel.warning);
ok = false;
}
if (MSDBox_Count >= Config.MSD_BOX_MAXCOUNT)
{
Msg.add("MSD箱已满", MsgLevel.warning);
ok = false;
}
if (PaperBox_Count >= Config.PAPER_BOX_MAXCOUNT)
{
Msg.add("Paper箱已满", MsgLevel.warning);
ok = false;
}
if (alarmType != AlarmType.SuddenStop)
{
TimeSpan span = DateTime.Now - checkAlarmTime;
//在回原点,复位,出入库时,检测报警间隔减小
if ((!runStatus.Equals(RunStatus.Stop) && span.TotalSeconds > 3) || span.TotalSeconds > 1)
{
foreach (ConfigMoveAxis configMoveAxis in Config.moveAxisList)
{
if (AxisManager.GetAlarmStatus(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue()) == 1)
{
Msg.add($"{configMoveAxis.DeviceName}:运动报警", MsgLevel.warning);
ok = false;
}
}
}
}
return ok;
}
public void BeginHomeReset(bool firstRun = false)
{
if (!firstRun)
{
StopMove();
Thread.Sleep(500);
}
OpenAllServo();
alarmType = AlarmType.None;
runStatus = RunStatus.HomeReset;
ResetMoveInfo.NewMove(MoveStep.H01_HomeReset);
ResetMoveInfo.log("开始回原");
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
}
private void HomeReset()
{
if (CheckWait(ResetMoveInfo))
return;
switch (ResetMoveInfo.MoveStep)
{
case MoveStep.H01_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H02_HomeReset);
ResetMoveInfo.log("正在回原, 所有阻挡上升");
CylinderMove(ResetMoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.HIGH);
CylinderMove(ResetMoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.HIGH);
CylinderMove(ResetMoveInfo, IO_Filter_Type.MSD_TaryStop_Down, IO_Filter_Type.MSD_TaryStop_Up, IO_VALUE.HIGH);
break;
case MoveStep.H02_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H03_HomeReset);
ResetMoveInfo.log("正在回原");
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.HIGH);
break;
case MoveStep.H03_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H04_HomeReset);
ResetMoveInfo.log("正在回原");
CylinderMove(ResetMoveInfo, IO_Filter_Type.NG_GetOut_Bck, IO_Filter_Type.NG_GetOut_Fwd, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_Filter_Type.Paper_GetOut_Bck, IO_Filter_Type.Paper_GetOut_Fwd, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_Filter_Type.MSD_GetOut_Bck, IO_Filter_Type.MSD_GetOut_Fwd, IO_VALUE.LOW);
break;
case MoveStep.H04_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H05_HomeReset);
MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
break;
case MoveStep.H05_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.HEND_HomeReset);
ResetMoveInfo.log("正在回原, 所有阻挡下升");
CylinderMove(ResetMoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_Filter_Type.MSD_TaryStop_Down, IO_Filter_Type.MSD_TaryStop_Up, IO_VALUE.LOW);
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
break;
case MoveStep.HEND_HomeReset:
ResetMoveInfo.log("回源完成");
ResetMoveInfo.EndMove();
MoveInfo.NewMove(MoveStep.Filter_01_WaitReel);
runStatus = RunStatus.Running;
break;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OnlineStore.LoadCSVLibrary;
namespace DeviceLibrary
{
public partial class FilterMachine
{
public bool isWaitReel { get => MoveInfo.MoveStep == MoveStep.Filter_01_WaitReel; }
public void LineRun(int sec = 0) {
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.HIGH, false, sec);
}
public IO_VALUE Tray_Check
{
get => IOValue(IO_Filter_Type.NG_TaryStop_Check);
}
void WorkProcess()
{
if (CheckWait(MoveInfo))
return;
switch (MoveInfo.MoveStep)
{
case MoveStep.Filter_01_WaitReel:
//MoveInfo.log("上料区阻挡上升");
if (IOValue(IO_Filter_Type.NG_TaryStop_Check).Equals(IO_VALUE.HIGH) && preReelParam != null)
{
MoveInfo.ReelParam = preReelParam;
preReelParam = null;
MoveInfo.log("检测到料盘 ReelParam:" + MoveInfo.ReelParam.ToStr());
//MoveInfo.ReelParam.ReelDest = ReelDest.String;
if (MoveInfo.ReelParam.ReelDest == ReelDest.NG || MoveInfo.ReelParam.ReelDest == ReelDest.Unknow)
{
MoveInfo.NextMoveStep(MoveStep.Filter_10_NGReel_PushOut);
MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(2000));
}
else if (MoveInfo.ReelParam.ReelDest == ReelDest.MSD)
{
MoveInfo.NextMoveStep(MoveStep.Filter_20_MSDReel_wait);
}
else if (MoveInfo.ReelParam.ReelDest == ReelDest.Paper)
{
MoveInfo.NextMoveStep(MoveStep.Filter_30_PaperReel_wait);
}
else if (MoveInfo.ReelParam.ReelDest == ReelDest.String)
{
MoveInfo.NextMoveStep(MoveStep.Filter_40_Reel_through_wait);
}
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.HIGH);
}
else if (IOValue(IO_Filter_Type.NG_TaryStop_Check).Equals(IO_VALUE.HIGH) && preReelParam == null)
{
Msg.add("分盘线等待料盘信息", MsgLevel.warning);
}
else
{
Msg.add($"等待进入料盘", MsgLevel.info);
}
break;
///NG料送出
case MoveStep.Filter_10_NGReel_PushOut:
MoveInfo.NextMoveStep(MoveStep.Filter_11_NGReel_End);
MoveInfo.log("NG料推出");
NGBox_Count++;
CylinderMove(MoveInfo, IO_Filter_Type.NG_GetOut_Bck, IO_Filter_Type.NG_GetOut_Fwd, IO_VALUE.HIGH);
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
break;
case MoveStep.Filter_11_NGReel_End:
MoveInfo.NextMoveStep(MoveStep.Filter_END);
MoveInfo.log("NG料推出完毕");
CylinderMove(MoveInfo, IO_Filter_Type.NG_GetOut_Bck, IO_Filter_Type.NG_GetOut_Fwd, IO_VALUE.LOW);
break;
///Paper料送出
case MoveStep.Filter_30_PaperReel_wait:
MoveInfo.NextMoveStep(MoveStep.Filter_31_PaperReel_PushOut);
MoveInfo.log("Paper料进入,NG阻挡上升");
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.HIGH);
MoveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Filter_Type.Paper_TaryStop_Check, IO_VALUE.HIGH));
break;
case MoveStep.Filter_31_PaperReel_PushOut:
MoveInfo.NextMoveStep(MoveStep.Filter_32_PaperReel_PushOut);
MoveInfo.log("Paper料等到到位");
MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(3000));
break;
case MoveStep.Filter_32_PaperReel_PushOut:
MoveInfo.NextMoveStep(MoveStep.Filter_33_PaperReel_End);
MoveInfo.log("Paper料推出");
PaperBox_Count++;
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.Paper_GetOut_Bck, IO_Filter_Type.Paper_GetOut_Fwd, IO_VALUE.HIGH);
break;
case MoveStep.Filter_33_PaperReel_End:
MoveInfo.log("Paper料推出完毕");
CylinderMove(MoveInfo, IO_Filter_Type.Paper_GetOut_Bck, IO_Filter_Type.Paper_GetOut_Fwd, IO_VALUE.LOW);
MoveInfo.NextMoveStep(MoveStep.Filter_END);
break;
///MSD料送出
case MoveStep.Filter_20_MSDReel_wait:
MoveInfo.NextMoveStep(MoveStep.Filter_21_MSDReel_wait);
MoveInfo.log("MSD料推出,NG阻挡上升");
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.HIGH);
CylinderMove(MoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.HIGH);
MoveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Filter_Type.MSD_TaryStop_Check, IO_VALUE.HIGH));
break;
case MoveStep.Filter_21_MSDReel_wait:
MoveInfo.NextMoveStep(MoveStep.Filter_22_MSDReel_PushOut);
MoveInfo.log("MSD料进入,等待");
MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(3000));
break;
case MoveStep.Filter_22_MSDReel_PushOut:
MoveInfo.NextMoveStep(MoveStep.Filter_23_MSDReel_End);
MoveInfo.log("MSD料推出");
MSDBox_Count++;
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.MSD_GetOut_Bck, IO_Filter_Type.MSD_GetOut_Fwd, IO_VALUE.HIGH);
break;
case MoveStep.Filter_23_MSDReel_End:
MoveInfo.NextMoveStep(MoveStep.Filter_END);
MoveInfo.log("MSD料推出完毕");
CylinderMove(MoveInfo, IO_Filter_Type.MSD_GetOut_Bck, IO_Filter_Type.MSD_GetOut_Fwd, IO_VALUE.LOW);
break;
///料穿过
case MoveStep.Filter_40_Reel_through_wait:
MoveInfo.NextMoveStep(MoveStep.Filter_41_Reel_through);
MoveInfo.log("料穿过,NG,Paper阻挡上升");
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.HIGH);
CylinderMove(MoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.HIGH);
MoveInfo.WaitList.Add(WaitResultInfo.WaitIO(IO_Filter_Type.MSD_TaryStop_Check, IO_VALUE.HIGH));
break;
case MoveStep.Filter_41_Reel_through:
if (RobotManage.t1Machine.TrayCanIN())
{
MoveInfo.NextMoveStep(MoveStep.Filter_42_Reel_through_Wait);
MoveInfo.log("料穿过,MSD阻挡上升,NG,Paper阻挡下降");
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.MSD_TaryStop_Down, IO_Filter_Type.MSD_TaryStop_Up, IO_VALUE.HIGH);
//CylinderMove(MoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.LOW);
RobotManage.t1Machine.preReelParam = MoveInfo.ReelParam;
RobotManage.t1Machine.LineRun();
MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(15000));
}
else if (MoveInfo.IsTimeOut(10)) {
Msg.add("等待T1机构空闲", MsgLevel.warning);
}
break;
case MoveStep.Filter_42_Reel_through_Wait:
MoveInfo.NextMoveStep(MoveStep.Filter_END);
MoveInfo.log("料穿过完成");
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
//MoveInfo.WaitList.Add(WaitResultInfo.WaitTime(5000));
break;
case MoveStep.Filter_END:
MoveInfo.NewMove(MoveStep.Filter_01_WaitReel);
MoveInfo.log("分料完成");
IOMove(IO_Filter_Type.Line3_Run, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.NG_TaryStop_Down, IO_Filter_Type.NG_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.MSD_TaryStop_Down, IO_Filter_Type.MSD_TaryStop_Up, IO_VALUE.LOW);
CylinderMove(MoveInfo, IO_Filter_Type.Paper_TaryStop_Down, IO_Filter_Type.Paper_TaryStop_Up, IO_VALUE.LOW);
break;
}
}
}
}
using CodeLibrary;
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 DeviceLibrary
{
public partial class LabelMachine
{
Led AlarmLed;
Led RunningLed;
System.Threading.Timer ledtimer;
private void LedProcessInit()
{
AlarmLed = new Led(Config.DOList[IO_Label_Type.Alarm_Led].GetIOAddr(),DeviceName);
RunningLed = new Led(Config.DOList[IO_Label_Type.Run_Led].GetIOAddr(), DeviceName);
ledtimer = new System.Threading.Timer(new TimerCallback(LedProcess), null, 0, 1000);
GC.KeepAlive(ledtimer);
}
void LedProcess(object o)
{
AlarmLed.LedState = LedState.off;
RunningLed.LedState = LedState.off;
if (runStatus == RunStatus.Running)
{
RunningLed.LedState = LedState.on;
//无法运行,量报警灯
if (!canRunning)
{
AlarmLed.LedState = LedState.on;
RunningLed.LedState = LedState.off;
}
if (MoveInfo.MoveStep == MoveStep.Lbl_WaitCheckLabel)
{
AlarmLed.LedState = LedState.blink;
}
else
{
}
}
else if (runStatus == RunStatus.HomeReset)
{
RunningLed.LedState = LedState.blink;
}
if (alarmType != AlarmType.None)
{
AlarmLed.LedState = LedState.on;
}
Led.LedGroup[DeviceName].ForEach((x) => { x.run(); });
}
}
}
using CodeLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public partial class LabelMachine
{
/// <summary>
///
/// </summary>
/// <param name="Label_Pix_Point"></param>
/// <returns>XY轴贴标点,R轴角度</returns>
public (Point,double,bool) ClacLabel(Point Label_Pix_Point)
{
bool ReverseLabel = false;
int Right_Batch_X = Config.Right_Batch_X;
if (MoveInfo.ReelParam.PlateW == 13)
{
Right_Batch_X = Right_Batch_X + Config.Label_Offset_Pixel_13;
}
else if (MoveInfo.ReelParam.PlateW == 15)
{
Right_Batch_X = Right_Batch_X + Config.Label_Offset_Pixel_15;
}
//照片中料盘中心点像素位置
Point Center_Pix_Point = new Point(Right_Batch_X, Config.Right_Batch_Y);
//二维码坐标
//Point Label_Pix_Point = new Point(X, Y);
//中心点到二维码角度,右侧为0度,+180转换到左侧为0度
var angle = Common.getAngle(Center_Pix_Point, Label_Pix_Point)+180;
//中心点到二维码距离
var distance = Common.distance(Center_Pix_Point, Label_Pix_Point);
//中心点到标签中心的角度
double rr = 20;
var lr = Math.Cos(rr * Math.PI / 180);
//中心点到标签中心的距离
var ll = lr * distance;
//标签中心到盘心的坐标
var labelCenterAngle = rr + angle;
if (labelCenterAngle < 0)
labelCenterAngle = 360 + labelCenterAngle;
//标签中心的坐标
var labelCenter =Common.PointWithAngle(Center_Pix_Point, labelCenterAngle - 180, ll);
/*
//从二维码坐标开始, 往中心点坐标推移一定的距离,获得推移后的坐标
Point AxisPixPoint = Common.PointWithAngle(Label_Pix_Point, angle, Config.Label_R_Offset_Pixel);
//匹配角度与贴标旋转轴的角度差
var labelAngle = angle - Config.Label_R_Angle_Diff+360;
if (labelAngle > 360)
labelAngle -= 360;
*/
//因为标签不统一暂时改为以二维码为中心贴标
labelCenter = Label_Pix_Point;
labelCenterAngle = angle;
//贴标位置轴的像素坐标
Point AxisPixPoint = Common.PointWithAngle(labelCenter, labelCenterAngle, Config.Label_R_Offset_Pixel);
//计算贴标角度的脉冲值
if (labelCenterAngle > 335)
{
ReverseLabel = true;
labelCenterAngle -= 180;
}
int labelAxisPos = (int)((double)Config.Label_R_360 / 335 * (double)labelCenterAngle);
MoveInfo.log($"计算结果,Label_R_360:{Config.Label_R_360},贴标角度:{labelCenterAngle},R轴:{labelAxisPos}");
//计算贴标像素点位与图像中心点的差
Point p1 = new Point(AxisPixPoint.X - Config.Right_Batch_X, AxisPixPoint.Y - Center_Pix_Point.Y);
//计算像素*脉冲像素比得到脉冲值+中心点基准脉冲
var x = (int)(p1.X * Config.Cam_Pixel_X_Ratio) + Config.Label_X_Base;
var y = (int)(p1.Y * Config.Cam_Pixel_Y_Ratio) + Config.Label_Y_Base;
p1.X = x;
p1.Y = y;
MoveInfo.log($"计算结果,图像像素中心{Center_Pix_Point},二维码像素坐标{Label_Pix_Point},角度{angle},贴标角度{labelCenterAngle},贴标像素点位为{AxisPixPoint},轴点位为{p1},R轴{labelAxisPos},盘宽{MoveInfo.ReelParam.PlateW}");
if (saveLabelDebugBmp)
{
IOMove(IO_Label_Type.Camera_Led, IO_VALUE.HIGH);
Task.Delay(10).Wait();
Bitmap bitmap = Camera._cam.GrabOneImage(Config.CameraName);
IOMove(IO_Label_Type.Camera_Led, IO_VALUE.LOW);
bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
//Bitmap bitmap = new Bitmap("d:\\出料模块-20210424-043753-0162.bmp");
printLabelDebugBitmap(bitmap, Label_Pix_Point, Center_Pix_Point, AxisPixPoint, angle, p1, labelCenterAngle, labelAxisPos, labelCenter);
bitmap.Dispose();
}
return (p1, labelAxisPos, ReverseLabel);
}
void printLabelDebugBitmap(Bitmap srcbitmap, Point Label_Pix_Point, Point Center_Pix_Point, Point AxisPixPoint, double angle, Point AxisP1,double labelAngle,double labelAxisPos, Point labelCenter) {
SolidBrush blue = new SolidBrush(Color.BlueViolet);
SolidBrush red = new SolidBrush(Color.Red);
SolidBrush yeelow = new SolidBrush(Color.Yellow);
SolidBrush AliceBlue = new SolidBrush(Color.AliceBlue);
Font font = new Font(FontFamily.GenericSansSerif, 60);
Pen Greenpen = new Pen(Color.Green, 10);
Bitmap bitmap = new Bitmap(srcbitmap.Width, srcbitmap.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
Size pointsize = new Size(30, 30);
g.DrawImage(srcbitmap, 0, 0);
srcbitmap.Dispose();
g.FillEllipse(blue, new Rectangle(Label_Pix_Point, pointsize));
g.FillEllipse(yeelow, new Rectangle(Center_Pix_Point, pointsize));
g.FillEllipse(red, new Rectangle(AxisPixPoint, pointsize));
g.FillEllipse(AliceBlue, new Rectangle(labelCenter, pointsize));
g.DrawLine(Greenpen, AxisPixPoint, Label_Pix_Point);
g.DrawString($"angle:{angle}", font, blue, 0, 0);
g.DrawString($"AxisP1:{AxisP1}", font, red, 0, 80);
g.DrawString($"labelAngle:{labelAngle}/{labelAxisPos}", font, red, 0, 160);
g.Save();
Directory.CreateDirectory("/image/LabelDebug/");
bitmap.Save("/image/LabelDebug/" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+".jpg",ImageFormat.Jpeg);
g.Dispose();
}
}
}
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 DeviceLibrary
{
public partial class LabelMachine : MachineBase, IRobot
{
private Config_Label _config;
public new Config_Label Config
{
get => _config; set
{
base.Config = value;
_config = value;
}
}
public override string DeviceName { get; set; } = "贴标机构";
public bool canRunning { get; set; }
public bool isBusy { get; set; }
public bool isAlarm { get; set; }
//public RunStatus runStatus { get; set; }
//public bool UserPause { get; set; }
public bool IgnoreSafecheck { get; set; }
public bool IgnoreGratingSignal { get; set; }
AxisBean Label_X_Axis;
AxisBean Label_Y_Axis;
AxisBean Label_Z_Axis;
AxisBean Label_R_Axis;
public bool Init(out string msg)
{
msg = "";
try
{
string configFile = "config\\LabelConfig.csv";
Config = new Config_Label(0, "", configFile);
Config = (Config_Label)CSVConfigReader.LoadConfig<IO_Label_Type>(Config);
#region 初始化伺服轴
Label_X_Axis = new AxisBean(Config.Label_X_Axis, DeviceName);
Label_Y_Axis = new AxisBean(Config.Label_Y_Axis, DeviceName);
Label_Z_Axis = new AxisBean(Config.Label_Z_Axis, DeviceName);
Label_R_Axis = new AxisBean(Config.Label_R_Axis, DeviceName);
#endregion
MoveInfo = new MoveInfo(DeviceName);
ResetMoveInfo = MoveInfo;
LedProcessInit();
}
catch (Exception e)
{
msg = e.Message;
return false;
}
return true;
}
protected override void LoopProcess()
{
mstart = true;
while (mstart)
{
try
{
canRunning = DeviceCheck();
if (canRunning)
{
//BtnProcess();
canRunning = SafeCheck();
}
Thread.Sleep(stepDelaytime);
if (!canRunning || !mstart)
continue;
if (runStatus == RunStatus.Running)
{
//IOMonitor();
WorkProcess();
}
else if (runStatus == RunStatus.HomeReset)
{
HomeReset();
}
}
catch (Exception ex)
{
Msg.add(ex.Message, MsgLevel.warning);
LogUtil.error(DeviceName + " " + ex.ToString());
Thread.Sleep(stepDelaytime*5);
}
finally
{
ProcessMsgEventFire(Msg);
//ProcessMoveinfoEventFire(MoveInfo.List);
Msg.Clear();
}
}
LogUtil.info($"{DeviceName} 主线程已退出.");
}
public bool DeviceCheck()
{
bool ok = true;
if (IOValue(IO_Label_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
Alarm(AlarmType.SuddenStop);
Msg.add("急停中", MsgLevel.warning);
ok = false;
}
else if (alarmType == AlarmType.SuddenStop)
{
Msg.add("系统需要重置", MsgLevel.warning);
ok = false;
}
if (alarmType != AlarmType.SuddenStop)
{
TimeSpan span = DateTime.Now - checkAlarmTime;
//在回原点,复位,出入库时,检测报警间隔减小
if ((!runStatus.Equals(RunStatus.Stop) && span.TotalSeconds > 3) || span.TotalSeconds > 1)
{
if (Config.moveAxisList != null)
{
foreach (ConfigMoveAxis configMoveAxis in Config.moveAxisList)
{
if (AxisManager.GetAlarmStatus(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue()) == 1)
{
Msg.add($"{configMoveAxis.Explain}:运动报警", MsgLevel.warning);
ok = false;
}
}
}
}
}
return ok;
}
public void BeginHomeReset(bool firstRun = false)
{
if (!firstRun)
{
StopMove();
Thread.Sleep(500);
}
OpenAllServo();
alarmType = AlarmType.None;
runStatus = RunStatus.HomeReset;
ResetMoveInfo.NewMove(MoveStep.H01_HomeReset);
ResetMoveInfo.log("开始回原");
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
}
private void HomeReset()
{
if (CheckWait(ResetMoveInfo))
return;
switch (ResetMoveInfo.MoveStep)
{
case MoveStep.H01_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H02_HomeReset);
ResetMoveInfo.log("正在回原, 皮带线阻挡上升,贴标机构阻挡上升,z轴");
CylinderMove(ResetMoveInfo, IO_Label_Type.TrayStop_Down, IO_Label_Type.TrayStop_Up);
CylinderMove(ResetMoveInfo, IO_Label_Type.Label_Stop_Down, IO_Label_Type.Label_Stop_Up);
Label_Z_Axis.HomeMove(ResetMoveInfo);
break;
case MoveStep.H02_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H03_HomeReset);
ResetMoveInfo.log("正在回原 y轴");
IOMove(IO_Label_Type.Line1_Run, IO_VALUE.HIGH);
IOMove(IO_Label_Type.Line2_Run, IO_VALUE.HIGH);
Label_X_Axis.HomeMove(ResetMoveInfo);
break;
case MoveStep.H03_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H04_HomeReset);
ResetMoveInfo.log("正在回原 xyzr轴");
Label_R_Axis.HomeMove(ResetMoveInfo);
Label_Y_Axis.HomeMove(ResetMoveInfo);
break;
case MoveStep.H04_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H05_HomeReset);
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(500));
break;
case MoveStep.H05_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H06_HomeReset);
ResetMoveInfo.log("正在回原 等待2秒钟");
Label_Y_Axis.AbsMove(ResetMoveInfo, Config.Label_Y_P2, Config.Label_Y_P2_speed);
Label_X_Axis.AbsMove(ResetMoveInfo, Config.Label_X_P2, Config.Label_X_P2_speed);
Label_R_Axis.AbsMove(ResetMoveInfo, Config.Label_R_P2, Config.Label_R_P2_speed);
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(2000));
break;
case MoveStep.H06_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H07_HomeReset);
ResetMoveInfo.log("正在回原 xyzr轴到待机点");
Label_Z_Axis.AbsMove(ResetMoveInfo, Config.Label_Z_P1, Config.Label_Z_P1_speed);
break;
case MoveStep.H07_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.HEND_HomeReset);
ResetMoveInfo.log("正在回原 线体停止,阻挡下降");
IOMove(IO_Label_Type.Line1_Run, IO_VALUE.LOW);
IOMove(IO_Label_Type.Line2_Run, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_Label_Type.TrayStop_Up, IO_Label_Type.TrayStop_Down);
CylinderMove(ResetMoveInfo, IO_Label_Type.Label_Stop_Up, IO_Label_Type.Label_Stop_Down);
break;
case MoveStep.HEND_HomeReset:
ResetMoveInfo.log("回源完成");
ResetMoveInfo.EndMove();
MoveInfo.NewMove(MoveStep.Lbl_01_Wait_ATray);
runStatus = RunStatus.Running;
break;
}
}
public IO_VALUE Label_TaryStop_Check
{
get => IOValue(IO_Label_Type.Label_TaryStop_Check);
}
public void InLineRunControl(IO_VALUE iO_VALUE)
{
IOMove(IO_Label_Type.Line1_Run, iO_VALUE);
}
}
}
using CodeLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public partial class LabelMachine
{
public void InitPrint()
{
RobotManage.PrintBean.PrintStatusChanged += Print_PrintStatusChanged;
RobotManage.LoadPrintSetting();
}
public Asa.PrintLabel.PrinterStatus LastPrintStatus = Asa.PrintLabel.PrinterStatus.Unknown;
void Print_PrintStatusChanged(Asa.PrintLabel.PrinterStatus sta, string msg)
{
if (sta.Equals(LastPrintStatus).Equals(false))
{
LogUtil.info("PrintLabel 收到打印机新状态:【" + sta + "】【" + msg + "】,替换原来的状态【" + LastPrintStatus + "】 ");
}
else
{
if (sta == Asa.PrintLabel.PrinterStatus.Idle)
{
Task.Run(() => {
while (true)
{
if (MoveInfo.IsStep(MoveStep.Lbl_WaitPrint))
{
MoveInfo.NextMoveStep(MoveStep.Lbl_Printted);
break;
}
Task.Delay(500).Wait();
}
});
}
LogUtil.info(" PrintLabel 收到打印机新状态:【" + sta + "】【" + msg + "】,与之前状态一样 ");
}
LastPrintStatus = sta;
}
public string LastPrintLabel = "";
void StartPrintLabel(string wareCode, string wareCount, bool ReverseLabel=false)
{
try
{
LastPrintStatus = Asa.PrintLabel.PrinterStatus.Unknown;
LogUtil.info("调用 PrintLabel 打印标签 StartPrintLabel ,[" + wareCode + "] [" + wareCount + "] 开始");
Dictionary<string, string> text = new Dictionary<string, string>();
text.Add("Code", wareCode);
text.Add("Count", wareCount);
text.Add("DateTime", System.DateTime.Now.ToString("F"));
text.Add("FactoryCode", "");
LastPrintLabel = wareCode;
RobotManage.PrintBean.Rotate180 = ReverseLabel;
RobotManage.PrintBean.Print(text);
LogUtil.info("PrintLabel 打印标签 StartPrintLabel 结束 ");
}
catch (Exception ex)
{
LogUtil.error("PrintLabel 打印标签 StartPrintLabel 错误:" + ex.ToString());
}
}
public Task DoPrint(ReelParam labelParam, bool ReverseLabel = false)
{
LogUtil.info($"调用 PrintLabel 打印标签 WareCode:{labelParam.WareCode}, QTY:{labelParam.QTY}, ReverseLabel:{ReverseLabel}");
StartPrintLabel(labelParam.WareCode, labelParam.QTY.ToString(), ReverseLabel);
return Task.Run(() =>
{ });
}
/// <summary>
/// 扫码线程
/// </summary>
Task<List<CodeInfo>> ScanTask;
Task<List<CodeInfo>> ScanCode()
{
MoveInfo.log("开始贴标扫码线程");
return Task.Run(new Func<List<CodeInfo>>(() =>
{
try
{
IOMove(IO_Label_Type.Camera_Led, IO_VALUE.HIGH);
Task.Delay(10).Wait();
List<CodeInfo> LastCodeList = CodeManager.CameraScan(new List<string> { Config.CameraName });
if (LastCodeList.Count <= 0)
{
Task.Delay(500).Wait();
LastCodeList = CodeManager.CameraScan(new List<string> { Config.CameraName });
}
IOMove(IO_Label_Type.Camera_Led, IO_VALUE.LOW);
return LastCodeList;
}
catch {
return new List<CodeInfo>();
}
}));
}
}
}
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 DeviceLibrary
{
partial class MainMachine
{
public void StopMove(bool ServoOff=false)
{
runStatus = RunStatus.Stop;
ResetMoveInfo.EndMove();
RightMoveInfo.EndMove();
LeftMoveInfo.EndMove();
LabelMoveInfo.EndMove();
MiddleMoveInfo.EndMove();
AxisBean.StopMultiAxis(AxisBean.List);
if (ServoOff)
AxisBean.CloseMultiAxis(AxisBean.List);
}
public void OpenAllServo()
{
AxisBean.RunMultiAxis(true, out _, AxisBean.List);
}
int logType = 1000;
string WarnMsg = "";
bool CheckWait(MoveInfo MoveInfo)
{
//当等待超过一分钟时,需要打印提示
TimeSpan span = DateTime.Now - MoveInfo.LastSetpTime;
string NotOkMsg = "";
if (MoveInfo.WaitList.Count <= 0)
{
MoveInfo.EndStepWait();
return false;
}
bool isOk = true;
if (MoveInfo.OneWaitCanEndStep)
{
isOk = false;
}
foreach (WaitResultInfo wait in MoveInfo.WaitList)
{
if (wait.IsEnd)
{
if (!wait.WaitType.Equals(WaitEnum.W002_IOValue))
{
continue;
}
}
NotOkMsg = wait.ToStr();
if (wait.WaitType.Equals(WaitEnum.W001_AxisMove))
{
string msg = "";
if (wait.IsHomeMove)
{
wait.IsEnd = AxisBean.HomeMoveIsEnd(MoveInfo, wait.AxisInfo, out msg);
}
else
{
wait.IsEnd = AxisBean.ACAxisMoveIsEnd(MoveInfo, wait.AxisInfo, wait.TargetPosition, wait.TargetSpeed, out msg);
}
if (!msg.Equals(""))
{
isOk = false;
WarnMsg = msg;
Alarm(AlarmType.AxisMoveError, WarnMsg);
Msg.add(WarnMsg, MsgLevel.warning);
break;
}
}
else if (wait.WaitType.Equals(WaitEnum.W002_IOValue))
{
ConfigIO io = RobotManage.Config.getWaitIO(wait.IoType);
NotOkMsg = " 等待【" + io.DisplayStr + "】=【" + wait.IoValue + "】";
wait.IsEnd = IOManager.IOValue(wait.IoType).Equals(wait.IoValue);
if (!wait.IsEnd)
{
int timeOutMs = 0;//RobotManage.Config.IOSingle_TimerOut;
if (span.TotalMilliseconds > timeOutMs && NoAlarm())
{
WarnMsg = Name + "[" + MoveInfo.MoveStep + "] 等待(" + io.DisplayStr + "=" + wait.IoValue + ") 超时";
Alarm(AlarmType.IoSingleTimeOut, WarnMsg);
Msg.add(WarnMsg, MsgLevel.warning);
LogUtil.error(WarnMsg, logType + 14);
//MoveInfo.errlog(WarnMsg);
if (!MoveInfo.OneWaitCanEndStep)
{
isOk = false;
break;
}
}
}
}
else if (wait.WaitType.Equals(WaitEnum.W003_Time))
{
wait.IsEnd = (span.TotalMilliseconds >= wait.TimeMSeconds);
}
else if (wait.WaitType.Equals(WaitEnum.W013_Action))
{
wait.IsEnd = wait.Action.Invoke(wait);
LogUtil.info($"{Name} 自定义等待 IsEnd={wait.IsEnd},Type={wait.Action.GetType()}");
}
else if (wait.WaitType.Equals(WaitEnum.W008_BatchAxis))
{
AxisBean axisBean;
if (wait.AxisInfo.ProName == "Right_Batch_Axis")
axisBean = Right_Batch_Axis;
else
axisBean = Left_Batch_Axis;
//等待信号亮或者走到绝对位置才停止
if (IOValue(axisBean.TargetIoType).Equals(axisBean.TargetIoValue))
{
LogUtil.debug(Name + "CheckWaitResult 检测到" + axisBean.TargetIoType + "=" + axisBean.TargetIoValue + ",停止运行");
axisBean.StopAxisCheckMove();
if (AxisManager.GetBusyStatus(wait.AxisInfo.DeviceName, wait.AxisInfo.GetAxisValue()).Equals(1))
{
axisBean.SuddenStop();
}
wait.IsEnd=true;
}
else
{
bool _isOk = AxisManager.GetBusyStatus(wait.AxisInfo.DeviceName, wait.AxisInfo.GetAxisValue()).Equals(0);
if (_isOk)
{
//TODO 判断是否达到高度,如果未达到,继续上升
axisBean.StopAxisCheckMove();
wait.IsEnd= true;
}
}
}
if (wait.IsEnd)
{
if (MoveInfo.OneWaitCanEndStep)
{
isOk = true;
break;
}
}
else
{
if (!MoveInfo.OneWaitCanEndStep)
{
isOk = false;
break;
}
}
}
if (isOk)
{
MoveInfo.EndStepWait();
return false;
}
else if (span.TotalSeconds > MoveInfo.TimeOutSeconds)
{
WarnMsg = Name + "[" + MoveInfo.MoveStep + "]等待" + NotOkMsg + "超时[" + Math.Round(span.TotalSeconds, 1) + "]秒";
int second = (int)(MoveInfo.TimeOutSeconds / span.TotalSeconds) * 10;
if (second > 120)
{
second = 120;
}
else if (second < 10)
{
second = 10;
}
LogUtil.error(WarnMsg, logType + 100, second);
//MoveInfo.errlog(WarnMsg);
Alarm(AlarmType.IoSingleTimeOut, WarnMsg);
Msg.add(WarnMsg, MsgLevel.warning);
}
return true;
}
/// <summary>
/// 是否再报警中
/// </summary>
AlarmType alarmType = AlarmType.None;
DateTime LastAlarmTime = DateTime.Now;
public void Alarm(AlarmType alarmType, string alarmMsg = "")
{
if (alarmType.Equals(AlarmType.None).Equals(false))
{
LastAlarmTime = DateTime.Now;
}
//SaveAlarmInfo(alarmType, alarmDetial, alarmMsg, storeMoveType);
if (this.alarmType.Equals(alarmType))
{
return;
}
LogUtil.error(Name + " 报警,报警类型:" + alarmType);
this.alarmType = alarmType;
if (alarmType.Equals(AlarmType.AxisAlarm) || alarmType.Equals(AlarmType.AxisMoveError))
{
LogUtil.error(Name + "轴报警, 停止运动, 打开报警灯");
StopMove(true);
}
else if (alarmType == AlarmType.SuddenStop)
{
//isInSuddenDown = true;
LogUtil.error(Name + "收到急停信号,停止运动, 打开报警灯 ");
StopMove(true);
//storeStatus = StoreStatus.SuddenStop;
}
else if (alarmType.Equals(AlarmType.NoAirCheck))
{
//isNoAirCheck = true;
LogUtil.error(Name + " 未检测到气压信号 ,停止运动, 打开报警灯 ");
StopMove(true);
//storeStatus = StoreStatus.SuddenStop;
}
}
internal bool NoAlarm()
{
if (alarmType.Equals(AlarmType.None))
{
return true;
}
return false;
}
public void CylinderMove(MoveInfo moveInfo, string IoLowType, string IoHighType)
{
IOMove(IoLowType, IO_VALUE.LOW);
IOMove(IoHighType, IO_VALUE.HIGH);
if (moveInfo != null)
{
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoLowType, IO_VALUE.LOW));
moveInfo.WaitList.Add(WaitResultInfo.WaitIO(IoHighType, IO_VALUE.HIGH));
}
}
IO_VALUE IOValue(string ioType) {
return IOManager.IOValue(ioType);
}
void IOMove(string IoType, IO_VALUE value, bool isCheck = false, int msTime = 0)
{
if (msTime <= 0)
{
if (isCheck && (IOValue(IoType).Equals(value)))
{
return;
}
IOManager.IOMove(IoType, value);
}
else
{
Task.Run(()=>
{
IOManager.IOMove(IoType, value);
Thread.Sleep(msTime);
IO_VALUE tValue = value.Equals(IO_VALUE.HIGH) ? IO_VALUE.LOW : IO_VALUE.HIGH;
LogUtil.info(Name + "定时回写IO: [" + IoType + "]=[" + value + "],msTime=" + msTime);
IOManager.IOMove(IoType, tValue);
});
}
}
}
}
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;
using System.Windows.Forms;
namespace DeviceLibrary
{
public partial class MainMachine : IRobot
{
public string Name { get; set; } = "移载";
private bool _canRunning=true;
public bool canRunning
{
get { return _canRunning; }
set
{
if (_canRunning != value) {
Msg.setlogones();
}
_canRunning = value;
}
}
public bool isBusy { get; set; } = false;
public bool isAlarm { get; set; } = false;
public RunStatus runStatus { get; set; } = RunStatus.Stop;
public XRay_Config Config { get; set; }
public bool UserPause { get; set; } = false;
MoveInfo ResetMoveInfo;
/// <summary>
/// 右侧移动信息
/// </summary>
MoveInfo RightMoveInfo;
MoveInfo LeftMoveInfo;
MoveInfo LabelMoveInfo;
MoveInfo MiddleMoveInfo;
public delegate void ProcessMsg(List<Msg> msg);
public event ProcessMsg ProcessMsgEvent;
public delegate void ProcessMoveinfo(List<MoveInfo> moveinfoList);
public event ProcessMoveinfo ProcessMoveinfoEvent;
AxisBean Take_Middle_Axis;
AxisBean Take_UpDown_Axis;
AxisBean Left_Batch_Axis;
AxisBean Right_Batch_Axis;
AxisBean Label_X_Axis;
AxisBean Label_Y_Axis;
AxisBean Label_Z_Axis;
AxisBean Label_R_Axis;
ElectricGripper electricClamp;
/// <summary>
/// 开始运行的时间
/// </summary>
public DateTime StartTime { get; set; }
/// <summary>
/// 是否在急停中
/// </summary>
public bool isInSuddenDown = false;
public MainMachine(DeviceConfig _config) {
XRayConfig = (XRay_Config)_config;
}
/// <summary>
/// 整机启动变量,设置为false后将退出线程,只在停止时调用
/// </summary>
bool mstart=true;
public void Run() {
mstart = true;
while (mstart) {
try
{
canRunning = DeviceCheck();
if (canRunning)
{
//BtnProcess();
canRunning = SafeCheck();
}
Thread.Sleep(50);
if (!canRunning || !mstart)
continue;
if (runStatus == RunStatus.Running)
{
//IOMonitor();
//RightProcess();
//MiddleProcess();
//LeftProcess();
//LabelProcess();
}
else if (runStatus == RunStatus.HomeReset)
{
HomeReset();
}
}
catch (Exception ex)
{
Msg.add(ex.Message, MsgLevel.warning);
}
finally {
ProcessMsgEvent?.Invoke(Msg.get());
ProcessMoveinfoEvent?.Invoke(MoveInfo.List);
Msg.clear();
}
}
LogUtil.info("主线程已退出.");
}
public void Stop() {
mstart = false;
StopMove(true);
}
public void BeginHomeReset(bool firstRun=false) {
if (!firstRun)
{
StopMove();
Thread.Sleep(500);
}
OpenAllServo();
alarmType = AlarmType.None;
runStatus = RunStatus.HomeReset;
ResetMoveInfo.NewMove(MoveStep.H01_HomeReset);
ResetMoveInfo.log("开始回原");
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
}
void HomeReset()
{
if (CheckWait(ResetMoveInfo))
return;
switch (ResetMoveInfo.MoveStep)
{
case MoveStep.H01_HomeReset:
break;
case MoveStep.HEND_HomeReset:
ResetMoveInfo.log("回源完成");
ResetMoveInfo.EndMove();
MiddleMoveInfo.NewMove(MoveStep.M_Standby);
LabelMoveInfo.NewMove(MoveStep.Lbl01);
runStatus = RunStatus.Running;
break;
}
}
public bool IgnoreSafecheck=false;
public bool IgnoreGratingSignal = false;
bool SafeCheck() {
bool ok = true;
if (UserPause)
{
Msg.add("用户暂停", MsgLevel.warning);
ok = false;
}/*
if (IOValue(IO_Type.GratingSignal_Check).Equals(IO_VALUE.LOW))
{
if (!IgnoreSafecheck && !IgnoreGratingSignal
&& IOValue(IO_Type.RightCar_Check).Equals(IO_VALUE.LOW)
&& IOValue(IO_Type.LeftCar_Check).Equals(IO_VALUE.LOW))
ok = false;
Msg.add("安全光栅被遮挡"+(!ok?"[忽略]":""), MsgLevel.warning);
}
if (IOValue(IO_Type.HasNgBox).Equals(IO_VALUE.LOW))
{
Msg.add("没有检测到NG料箱", MsgLevel.warning);
ok = false;
}
if (IOValue(IO_Type.HasPrinter).Equals(IO_VALUE.LOW))
{
Msg.add("没有检测打印机", MsgLevel.warning);
ok = false;
}
if (IOValue(IO_Type.LeftBackDoor_Check).Equals(IO_VALUE.LOW))
{
Msg.add("左后门没有关闭", MsgLevel.warning);
if (!IgnoreSafecheck)
ok = false;
}
if (IOValue(IO_Type.RightBackDoor_Check).Equals(IO_VALUE.LOW))
{
Msg.add("右后门没有关闭", MsgLevel.warning);
if (!IgnoreSafecheck)
ok = false;
}(*/
return ok;
}
/// <summary>
/// 最后一次气压检测变为0的时间
/// </summary>
DateTime lastAirCloseTime = DateTime.MinValue;
internal DateTime checkAlarmTime = DateTime.Now;
public bool DeviceCheck() {
bool ok = true;
/*
if (IOValue(IO_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
Alarm(AlarmType.SuddenStop);
Msg.add("急停中", MsgLevel.warning);
ok = false;
}
else if (alarmType == AlarmType.SuddenStop) {
Msg.add("系统需要重置", MsgLevel.info);
ok = false;
}
if (IOValue(IO_Type.Airpressure_Check).Equals(IO_VALUE.LOW))
{
if (lastAirCloseTime == DateTime.MinValue)
lastAirCloseTime = DateTime.Now;
TimeSpan span = DateTime.Now - lastAirCloseTime;
if (span.TotalSeconds > RobotManage.Config.AirCheckSeconds)
{
ok = false;
Msg.add("气压不足", MsgLevel.warning);
}
}
else {
lastAirCloseTime = DateTime.MinValue;
}
if (alarmType!=AlarmType.SuddenStop)
{
TimeSpan span = DateTime.Now - checkAlarmTime;
//在回原点,复位,出入库时,检测报警间隔减小
if ((!runStatus.Equals(RunStatus.Stop) && span.TotalSeconds > 3) || span.TotalSeconds > 1)
{
foreach (ConfigMoveAxis configMoveAxis in Config.moveAxisList)
{
if (AxisManager.GetAlarmStatus(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue()) == 1)
{
Msg.add($"{configMoveAxis.DeviceName}:运动报警", MsgLevel.warning);
ok = false;
}
}
}
}*/
return ok;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public enum MoveStep
{
Wait,
//回原流程
H01_HomeReset,
H02_HomeReset,
H03_HomeReset,
H04_HomeReset,
H05_HomeReset,
H06_HomeReset,
H07_HomeReset,
HEND_HomeReset,
Feeding_01_Wait_Detect,
Feeding_02_Take_Picture,
Feeding_03_Get_Reelinfo,
Feeding_04_Wait_Xray_Free,
Feeding_05_Wait_Man_Check,
Feeding_06_Goto_Xray,
Feeding_10_Wait_Reset,
Lbl_01_Wait_ATray,
Lbl_02_StopUP,
Lbl_03_LineRun,
Lbl_03_StopDown_and_wait,
Lbl_04_LineStopWait,
Lbl_04_LineStop,
Lbl_05_Get_Reelinfo,
//Lbl_01_StartPrint,
Lbl_WaitCheckLabel,
Lbl_WaitPrint,
Lbl_Printted,
Lbl01,
Lbl02,
Lbl03,
Lbl04,
Lbl05,
Lbl10,
Lbl11_wait,
Lbl11,
Lbl12,
Lbl13,
Lbl_BeginOut,
Lbl15,
Lbl16,
L30_LabelFinish,
Shelf_EmptyIn_WaitWorkLeave,
Shelf_10_EmptyIn_Wait_StopDown,
Shelf_10_EmptyIn_StopDown,
Shelf_11_EmptyIn_WaitTime,
Shelf_11_EmptyIn_LiftUp,
Shelf_13_EmptyIn_SidingRun,
Shelf_14_EmptyIn_LiftDown,
Shelf_15_EmptyIn_LocationUp,
Shelf_16_EmptyIn_ForkFwd,
Shelf_17_EmptyIn_CheckLocation,
Shelf_18_EmptyIn_WaitManCheck,
Shelf_19_EmptyIn_BatchUp,
Shelf_20_EmptyIn_ShelfReady,
Shelf_21_EmptyIn_TrayDown,
Shelf_Work_WaitShelfLeave,
Shelf_Out_Wait,
Shelf_30_Out_BatchDown,
Shelf_31_Out_ForkBck,
Shelf_32_Out_LocationDown,
Shelf_33_Out_OutStopDown,
Shelf_34_Out_OutStopDown,
Shelf_35_Out_OutLineRun,
Shelf_36_Out_OutLineRun,
XRay_01_LocationDown,
XRay_02_RunIn,
XRay_03_CloseDoor,
XRay_04_OpenXray,
XRay_05_GetImage,
XRay_06_GetCount,
XRay_07_CloseXray,
XRay_08_OpenOutDoor,
XRay_09_SentToLabelStop,
XRay_10_CloseOutDoor,
XRay_11_GetCoutResult,
XRay_End,
Filter_01_WaitReel,
Filter_02_WaitReel,
Filter_10_NGReel_PushOut,
Filter_11_NGReel_End,
Filter_20_MSDReel_wait,
Filter_21_MSDReel_wait,
Filter_22_MSDReel_PushOut,
Filter_23_MSDReel_End,
Filter_30_PaperReel_wait,
Filter_31_PaperReel_PushOut,
Filter_32_PaperReel_PushOut,
Filter_33_PaperReel_End,
Filter_40_Reel_through_wait,
Filter_41_Reel_through,
Filter_42_Reel_through_Wait,
Filter_END,
T1_01_WaitReel,
T1_02_WaitReelInpos,
T1_03_LocationUp,
T1_04_DownToReel,
T1_05_ClampReel,
T1_06_UpToTop,
T1_07_PanToOut,
T1_08_DownToShelf,
T1_09_ReleaseReel,
T1_10_PutReelFinish,
}
public enum AlarmType
{
/// <summary>
/// 没有报警
/// </summary>
None = 0,
/// <summary>
/// 轴报警
/// </summary>
AxisAlarm = 1,
/// <summary>
/// 收到急停
/// </summary>
SuddenStop = 10,
/// <summary>
/// 没有气压信号
/// </summary>
NoAirCheck = 11,
/// <summary>
/// 轴运动错误,没有达到指定脉冲,但是io判断已停止运动
/// </summary>
AxisMoveError = 20,
/// <summary>
/// io信号超时未收到
/// </summary>
IoSingleTimeOut = 30,
}
}
using Asa;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DeviceLibrary
{
public static class RobotManage
{
public static XRayMachine xrayMachine;
public static LabelMachine labelMachine;
public static FilterMachine filterMachine;
public static T1Machine t1Machine;
public static XRay XRay=new Asa.XRay("XRay");
public static XrayImage xrayImage = new Asa.XrayImage("XrayImage", XrayImage.DeviceType.HAOBO);
public static Config_XRay Config;
public static bool IsLoadOk = true;
public static bool IsDebug = false;
/// <summary>
///
/// </summary>
/// <param name="state">加载成功状态</param>
/// <param name="msg">加载消息</param>
public delegate void LoadFinish(bool state,string msg);
public static event LoadFinish LoadFinishEvent;
public static bool isRunning = false;
public static Asa.PrintLabel PrintBean;
public static ElectricGripper electricGripper;
public static List<IRobot> robots = new List<IRobot>();
public static WistonAgvClient wistonAgvClient;
//static string baseDir = Application.StartupPath;
public static void Init() {
try
{
string msgs = "";
xrayMachine = new XRayMachine();
labelMachine = new LabelMachine();
filterMachine = new FilterMachine();
t1Machine = new T1Machine();
wistonAgvClient = new WistonAgvClient();
robots.AddRange(new IRobot[] { xrayMachine, labelMachine, filterMachine, t1Machine });
//robots.AddRange(new IRobot[] { xrayMachine });
robots.ForEach((device)=> {
LogUtil.info(device.DeviceName + " init");
if (!device.Init(out string msg))
{
IsLoadOk = false;
msgs += $"{device.DeviceName} Init Failed\n";
}
LogUtil.info(device.DeviceName + " init end");
});
CodeManager.LoadConfig();
PrintBean = new Asa.PrintLabel(Application.StartupPath + "\\Label");
labelMachine.InitPrint();
if (!XRay.Open(ConfigHelper.Config.Get("XRay_Port"), string.Format("{0:yyyy-MM-dd}", DateTime.Now)))
{
msgs += $"X光管通讯失败:{ConfigHelper.Config.Get("XRay_Port")}\n";
IsLoadOk = false;
}
else
LogUtil.info("xray init ok");
if (XRay.SetVC(ConfigHelper.Config.Get("XRay_Voltage"), ConfigHelper.Config.Get("XRay_Current")))
{
msgs += $"X光电压电流设置失败:{ConfigHelper.Config.Get("XRay_Voltage")},{ConfigHelper.Config.Get("XRay_Current")}\n";
IsLoadOk = false;
}
else
LogUtil.info("xray VC set ok");
if (!xrayImage.Open()) {
msgs += $"图像平板打开失败\n";
IsLoadOk = false;
}
//xrayImage.Close();
var ElectricGripperPort = ConfigHelper.Config.Get("ElectricGripperPort");
electricGripper = new ElectricGripper();
if (!electricGripper.OpenPort(ElectricGripperPort)) {
msgs += $"电夹爪通讯失败:{ElectricGripperPort}\n";
IsLoadOk = false;
}
//mainMachine = new MainMachine(RobotManage.Config);
if (!IOManager.ConnectionIO())
{
IsLoadOk = false;
msgs += "IO板卡初始化失败\n";
}
LoadFinishEvent?.Invoke(IsDebug?IsDebug:IsLoadOk, msgs);
}
catch (Exception ex) {
LoadFinishEvent?.Invoke(false, ex.ToString());
LogUtil.error(ex.ToString());
}
}
public static void LoadDebug() {
LoadFinishEvent?.Invoke(true, "打开调试模式");
}
public static void Start()
{
if (!IsLoadOk)
{
LogUtil.info("系统还未加载完毕,无法启动");
if (!IsDebug)
return;
}
robots.ForEach((device) => device.Run());
isRunning = true;
Task.Run(() =>
{
Task.Delay(1000).Wait();
//开始初始化回原
robots.ForEach((device) =>
{
if (device.DeviceCheck())
device.BeginHomeReset(true);
});
});
}
public static void Stop()
{
LogUtil.info("开始停止系统.");
robots.ForEach((device) => device.Stop());
isRunning = false;
}
public static void ShutDown() {
LogUtil.info("开始关闭系统.");
IOManager.CloseAllConnection();
electricGripper.ClosePort();
}
public static void UserPause(bool userpause) {
//xrayMachine.UserPause = userpause;
robots.ForEach((device) => device.UserPause= userpause);
if (userpause)
LogUtil.info("用户暂停");
else
LogUtil.info("用户取消暂停");
}
public static void LoadPrintSetting()
{
string PrintName = ConfigHelper.Config.Get(Setting_Init.PrinterName);
string labelName = ConfigHelper.Config.Get(Setting_Init.LabelName);
PrintBean.LoadLabel(labelName);
PrintBean.Printer(PrintName, false);
LogUtil.info("PrintLabel 打印机初始化完成【" + labelName + "】【" + PrintName + "】");
}
}
}
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceLibrary
{
partial class T1Machine
{
Led AlarmLed;
Led RunningLed;
System.Threading.Timer ledtimer;
void LedProcessInit()
{
AlarmLed = new Led(Config.DOList[IO_T1_Type.Alarm_Led].GetIOAddr(), DeviceName);
RunningLed = new Led(Config.DOList[IO_T1_Type.Run_Led].GetIOAddr(), DeviceName);
ledtimer = new System.Threading.Timer(new TimerCallback(LedProcess), null, 0, 1000);
GC.KeepAlive(ledtimer);
}
void LedProcess(object o)
{
AlarmLed.LedState = LedState.off;
RunningLed.LedState = LedState.off;
if (runStatus == RunStatus.Running)
{
RunningLed.LedState = LedState.on;
//无法运行,量报警灯
if (!canRunning)
{
AlarmLed.LedState = LedState.on;
RunningLed.LedState = LedState.off;
}
if (ShelfInMoveInfo.MoveStep == MoveStep.Shelf_18_EmptyIn_WaitManCheck) {
AlarmLed.LedState = LedState.on;
}
}
else if (runStatus == RunStatus.HomeReset)
{
RunningLed.LedState = LedState.blink;
}
if (alarmType != AlarmType.None)
{
AlarmLed.LedState = LedState.on;
}
Led.LedGroup[DeviceName].ForEach((x) => { x.run(); });
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeLibrary;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
namespace DeviceLibrary
{
public partial class XRayMachine
{
MoveInfo FeedingMoveinfo = new MoveInfo("入料");
void FeedingProcess()
{
if (CheckWait(FeedingMoveinfo))
return;
switch (FeedingMoveinfo.MoveStep)
{
case MoveStep.Feeding_01_Wait_Detect:
if (TrayWidth == 0 || TrayHight == 0)
{
TrayMonitor();
}
else
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_02_Take_Picture);
FeedingMoveinfo.ReelParam.PlateW = TrayWidth;
FeedingMoveinfo.ReelParam.PlateH = TrayHight;
FeedingMoveinfo.log($"已稳定检测到料盘TrayWidth={TrayWidth},TrayHight={TrayHight}");
}
break;
case MoveStep.Feeding_02_Take_Picture:
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_03_Get_Reelinfo);
ScanCode();
break;
case MoveStep.Feeding_03_Get_Reelinfo:
if (ScanTask.IsCompleted)
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_04_Wait_Xray_Free);
//78.10222.20L-016651|-20200826|900|W78016651352000A6|SAMSUNG
var x = ScanTask.Result;
//x.Add(new CodeInfo("test", 1000, 1000));
if (x.Count != 1)
{
FeedingMoveinfo.log($"未识别到有效二维码,等待人工取走, Count={x.Count}");
FeedingMoveinfo.ReelParam.IsNg = true;
}
else
{
FeedingMoveinfo.ReelParam.IsNg = false;
FeedingMoveinfo.ReelParam.codeInfos = x;
FeedingMoveinfo.ReelParam.WareCode = x[0].CodeStr;
FeedingMoveinfo.log($"已完成扫码,等待料盘被通过按钮确认,Count={x.Count}");
}
}
else if (FeedingMoveinfo.IsTimeOut(10))
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_03_Get_Reelinfo);
FeedingMoveinfo.log($"等待扫码超时,重新扫码");
}
break;
case MoveStep.Feeding_04_Wait_Xray_Free:
if (MoveInfo.MoveStep == MoveStep.Wait)
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_05_Wait_Man_Check);
FeedingMoveinfo.log($"Xray已空闲,允许进入");
}
else if (FeedingMoveinfo.ReelParam.IsNg)
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_05_Wait_Man_Check);
FeedingMoveinfo.log($"NG料,进入人工取走步骤");
}
else if (MoveInfo.IsTimeOut(10))
{
FeedingMoveinfo.log($"等待Xray可以进入");
Msg.add("等待Xray可以进入", MsgLevel.info);
}
break;
case MoveStep.Feeding_05_Wait_Man_Check:
if (FeedingMoveinfo.ReelParam.IsNg)
{
if (IOValue(IO_XRay_Type.Tray_Check).Equals(IO_VALUE.HIGH))
{
Msg.add("未识别出料盘, 请取走", MsgLevel.warning);
}
else if (IOMonitor.IODebound(IO_XRay_Type.Tray_Check, Config, IO_VALUE.LOW, 1000))
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_10_Wait_Reset);
FeedingMoveinfo.log($"料盘已被人工取走");
}
}
else
{
if (true|| IOValue(IO_XRay_Type.Manual_Confirm_BTN).Equals(IO_VALUE.HIGH))
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_06_Goto_Xray);
FeedingMoveinfo.log($"按下入料按钮, 定位气缸下降");
CylinderMove(FeedingMoveinfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up, IO_VALUE.LOW);
}
else if (IOMonitor.IODebound(IO_XRay_Type.Tray_Check, Config, IO_VALUE.LOW, 2000))
{
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_10_Wait_Reset);
FeedingMoveinfo.log($"料盘已被人工取走");
}
}
break;
case MoveStep.Feeding_06_Goto_Xray:
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_10_Wait_Reset);
MoveInfo.NewMove(MoveStep.XRay_01_LocationDown);
MoveInfo.ReelParam = FeedingMoveinfo.ReelParam;
FeedingMoveinfo.WaitList.Add(WaitResultInfo.WaitTime(7000));
break;
case MoveStep.Feeding_10_Wait_Reset:
FeedingMoveinfo.NewMove(MoveStep.Feeding_01_Wait_Detect);
TrayWidth = 0;
TrayHight = 0;
SensorDebounce.Reset();
CylinderMove(FeedingMoveinfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up, IO_VALUE.HIGH);
break;
default:
FeedingMoveinfo.NextMoveStep(MoveStep.Feeding_10_Wait_Reset);
break;
}
}
/// <summary>
/// 扫码线程
/// </summary>
Task<List<CodeInfo>> ScanTask;
void ScanCode()
{
FeedingMoveinfo.log("开始扫码");
try
{
ScanTask = Task.Run(new Func<List<CodeInfo>>(() =>
{
IOMove(IO_XRay_Type.Camera_Led, IO_VALUE.HIGH);
Task.Delay(10).Wait();
List<CodeInfo> LastCodeList = CodeManager.CameraScan(new List<string> { Config.CameraName });
IOMove(IO_XRay_Type.Camera_Led, IO_VALUE.LOW);
return LastCodeList;
}));
}
catch (Exception ex)
{
LogUtil.error("扫码出错:", ex);
}
}
int TrayWidth = 0;
int TrayHight = 0;
void TrayMonitor() {
if (IOValue(IO_XRay_Type.Tray_Check).Equals(IO_VALUE.LOW))
{
SensorDebounce.Reset();
return;
}
int overhight = 70;
var Tray15_L = AdioValue(IO_XRay_Type.Tray15_L_ADIO);
var Tray15_R = AdioValue(IO_XRay_Type.Tray15_R_ADIO);
var Tray13_L = AdioValue(IO_XRay_Type.Tray13_L_ADIO);
var Tray13_R = AdioValue(IO_XRay_Type.Tray13_R_ADIO);
var Tray7_L = AdioValue(IO_XRay_Type.Tray7_L_ADIO);
var Tray7_R = AdioValue(IO_XRay_Type.Tray7_R_ADIO);
var Tray7= Math.Max(Tray7_L, Tray7_R);
var Tray13 = Math.Max(Tray13_L, Tray13_R);
var Tray15 = Math.Max(Tray15_L, Tray15_R);
//LogUtil.OutputDebugString($"Tray7:{Tray7},Tray13:{Tray13},Tray15:{Tray15}");
int v=0;
if (Tray15 < overhight)
{
if (SensorDebounce.Debounce(Tray15, out v))
TrayWidth = 15;
}
else if (Tray13 < overhight)
{
if (SensorDebounce.Debounce(Tray13, out v))
TrayWidth = 13;
}
else if (Tray7 < overhight)
{
if (SensorDebounce.Debounce(Tray7, out v))
TrayWidth = 7;
}
if (v>0)
FeedingMoveinfo.log($"Sensor Tray7:{Tray7},Tray13:{Tray13},Tray15:{Tray15}");
TrayHight = CalcHight(v);
}
int AdioValue(string ioType) {
var pi = Config.GetType().GetProperty(ioType + "_base");
var basevalue = (int)pi.GetValue(Config);
var value = IOManager.GetADIOValue(ioType, Config);
var c = ((int)value - basevalue) / Config.Tray_ADIO_Value;
return c;
}
int CalcHight(int height) {
int LastHeight = 0;
List<int> heightList = new List<int> {0, 8, 12, 16, 24, 32, 44, 56 };
//heightList = (from m in heightList orderby m descending select m).ToList<int>();
//float minCha = height;
foreach (int h in heightList)
{
if (height > h)
{
LastHeight = h;
}
}
return LastHeight;
}
}
}
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceLibrary
{
partial class XRayMachine
{
Led AlarmLed;
Led StandbyLed;
Led RunningLed;
Led TrayOKLed;
Led TrayNGLed;
System.Threading.Timer ledtimer;
void LedProcessInit()
{
AlarmLed = new Led(Config.DOList[IO_XRay_Type.Alarm_Led].GetIOAddr(), DeviceName);
StandbyLed = new Led(Config.DOList[IO_XRay_Type.Standby_Led].GetIOAddr(), DeviceName);
RunningLed = new Led(Config.DOList[IO_XRay_Type.Run_Led].GetIOAddr(), DeviceName);
TrayOKLed = new Led(Config.DOList[IO_XRay_Type.Pass_Led].GetIOAddr(), DeviceName);
TrayNGLed = new Led(Config.DOList[IO_XRay_Type.NG_Led].GetIOAddr(), DeviceName);
ledtimer = new System.Threading.Timer(new TimerCallback(LedProcess), null, 0, 1000);
GC.KeepAlive(ledtimer);
}
void LedProcess(object o)
{
AlarmLed.LedState = LedState.off;
//StandbyLed.LedState = LedState.off;
RunningLed.LedState = LedState.off;
if (runStatus == RunStatus.Running)
{
RunningLed.LedState = LedState.on;
//无法运行,量报警灯
if (!canRunning)
{
AlarmLed.LedState = LedState.on;
RunningLed.LedState = LedState.off;
}
//等待人工处理步骤
if (FeedingMoveinfo.IsStep(MoveStep.Feeding_05_Wait_Man_Check))
{
if (FeedingMoveinfo.ReelParam.IsNg)
{
TrayNGLed.LedState = LedState.blink;
}
else
{
TrayOKLed.LedState = LedState.blink;
}
}
else
{
TrayNGLed.LedState = LedState.off;
TrayOKLed.LedState = LedState.off;
}
}
else if (runStatus == RunStatus.HomeReset)
{
RunningLed.LedState = LedState.blink;
}
if (alarmType != AlarmType.None)
{
AlarmLed.LedState = LedState.on;
}
Led.LedGroup[DeviceName].ForEach((x) => { x.run(); });
}
}
}
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public partial class XRayMachine : MachineBase, IRobot
{
private Config_XRay _config;
public new Config_XRay Config
{
get => _config;
set
{
base.Config = value;
_config = value;
}
}
public override string DeviceName { get; set; } = "点料";
public bool canRunning { get; set; }
public bool isBusy { get; set; }
public bool isAlarm { get; set; }
//public RunStatus runStatus { get; set; }
//public override bool UserPause { get; set; }
public bool IgnoreSafecheck { get; set; }
public bool IgnoreGratingSignal { get; set; }
AxisBean Line_Entry_Axis;
AxisBean Line_In_Axis;
public bool Init(out string msg)
{
msg = "";
try
{
string configFile = "config\\XrayConfig.csv";
Config = new Config_XRay(0, "", configFile);
Config = (Config_XRay)CSVConfigReader.LoadConfig<IO_XRay_Type>(Config);
LogUtil.info(DeviceName + " config load finish");
#region 初始化伺服轴
Line_Entry_Axis = new AxisBean(Config.Line_Entry_Axis, DeviceName);
Line_In_Axis = new AxisBean(Config.Line_In_Axis, DeviceName);
#endregion
MoveInfo = new MoveInfo(DeviceName);
ResetMoveInfo = MoveInfo;
LedProcessInit();
IOMonitor.RegisterIO(IO_XRay_Type.Exit_Open, Config, IO_VALUE.LOW, delegate () { XRayDoorOpen(); });
IOMonitor.RegisterIO(IO_XRay_Type.Entry_Open, Config, IO_VALUE.LOW, delegate () { XRayDoorOpen(); });
LogUtil.info(DeviceName + " init end");
}
catch (Exception e){
msg = e.Message;
return false;
}
return true;
}
void XRayDoorOpen() {
if (RobotManage.XRay.IsRayOpen)
{
LogUtil.info(DeviceName + " X光机防护门打开");
RobotManage.XRay.Stop();
IOMove(IO_XRay_Type.Xray_Lock, IO_VALUE.LOW);
}
else {
LogUtil.info(DeviceName + " X光没有打开");
}
}
protected override void LoopProcess()
{
mstart = true;
while (mstart)
{
try
{
canRunning = DeviceCheck();
if (canRunning)
{
canRunning = SafeCheck();
}
Thread.Sleep(stepDelaytime);
if (!canRunning || !mstart)
continue;
if (runStatus == RunStatus.Running)
{
FeedingProcess();
WorkProcess();
}
else if (runStatus == RunStatus.HomeReset)
{
HomeReset();
}
}
catch (Exception ex)
{
Msg.add(ex.Message, MsgLevel.warning);
LogUtil.error(DeviceName + " " + ex.ToString());
}
finally
{
ProcessMsgEventFire(Msg);
//ProcessMoveinfoEventFire(MoveInfo.List);
Msg.Clear();
}
}
LogUtil.info($"{DeviceName} 主线程已退出.");
}
/// <summary>
/// 最后一次气压检测变为0的时间
/// </summary>
DateTime lastAirCloseTime = DateTime.MinValue;
public bool DeviceCheck() {
//return true;
bool ok = true;
if (IOValue(IO_XRay_Type.SuddenStop_BTN).Equals(IO_VALUE.LOW))
{
Alarm(AlarmType.SuddenStop);
Msg.add("急停中", MsgLevel.warning);
ok = false;
}
else if (alarmType == AlarmType.SuddenStop)
{
Msg.add("系统需要重置", MsgLevel.info);
ok = false;
}
if (IOValue(IO_XRay_Type.Airpressure_Check).Equals(IO_VALUE.LOW))
{
if (lastAirCloseTime == DateTime.MinValue)
lastAirCloseTime = DateTime.Now;
TimeSpan span = DateTime.Now - lastAirCloseTime;
if (span.TotalSeconds > Config.AirCheckSeconds)
{
ok = false;
Msg.add("气压不足", MsgLevel.warning);
}
}
else
{
lastAirCloseTime = DateTime.MinValue;
}
if (alarmType != AlarmType.SuddenStop)
{
TimeSpan span = DateTime.Now - checkAlarmTime;
//在回原点,复位,出入库时,检测报警间隔减小
if ((!runStatus.Equals(RunStatus.Stop) && span.TotalSeconds > 3) || span.TotalSeconds > 1)
{
foreach (ConfigMoveAxis configMoveAxis in Config.moveAxisList)
{
if (AxisManager.GetAlarmStatus(configMoveAxis.DeviceName, configMoveAxis.GetAxisValue()) == 1)
{
Msg.add($"{configMoveAxis.Explain}:运动报警", MsgLevel.warning);
ok = false;
}
}
}
}
return ok;
}
public void BeginHomeReset(bool firstRun = false)
{
if (!firstRun)
{
StopMove();
Thread.Sleep(500);
}
OpenAllServo();
alarmType = AlarmType.None;
runStatus = RunStatus.HomeReset;
ResetMoveInfo.NewMove(MoveStep.H01_HomeReset);
ResetMoveInfo.log("开始回原");
ResetMoveInfo.WaitList.Add(WaitResultInfo.WaitTime(1000));
}
private void HomeReset()
{
if (CheckWait(ResetMoveInfo))
return;
switch (ResetMoveInfo.MoveStep)
{
case MoveStep.H01_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H02_HomeReset);
ResetMoveInfo.log("正在回原, 托盘下降,门打开");
CylinderMove(ResetMoveInfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up,IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_XRay_Type.Entry_Close, IO_XRay_Type.Entry_Open);
CylinderMove(ResetMoveInfo, IO_XRay_Type.Exit_Close, IO_XRay_Type.Exit_Open);
break;
case MoveStep.H02_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.H03_HomeReset);
Line_Entry_Axis.RelMove(ResetMoveInfo, Config.Line_Entry_Relative*2, Config.Line_Entry_Relative_speed);
Line_In_Axis.RelMove(ResetMoveInfo, Config.Line_In_Relative*2, Config.Line_In_Relative_speed);
ResetMoveInfo.log("正在回原");
break;
case MoveStep.H03_HomeReset:
ResetMoveInfo.NextMoveStep(MoveStep.HEND_HomeReset);
ResetMoveInfo.log("正在回原, 门关闭");
CylinderMove(ResetMoveInfo, IO_XRay_Type.Entry_Close, IO_XRay_Type.Entry_Open,IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_XRay_Type.Exit_Close, IO_XRay_Type.Exit_Open, IO_VALUE.LOW);
CylinderMove(ResetMoveInfo, IO_XRay_Type.Location_Cylinder_Down, IO_XRay_Type.Location_Cylinder_Up, IO_VALUE.HIGH);
break;
case MoveStep.HEND_HomeReset:
ResetMoveInfo.log("回源完成");
ResetMoveInfo.EndMove();
//MoveInfo.NewMove(MoveStep.Feeding_05_Goto_Xray);
runStatus = RunStatus.Running;
break;
}
}
}
}
using CodeLibrary;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceLibrary
{
public class Common
{
/// <summary>
/// 获取角度
/// 求3点形成的夹角
/// </summary>
/// <param name="pt1"></param>
/// <param name="pt2"></param>
/// <param name="pt0">顶角</param>
/// <returns></returns>
public static float getAngle2(Point pt1, Point pt2, Point pt0)
{
double ma_x = pt1.X - pt0.X;
double ma_y = pt1.Y - pt0.Y;
double mb_x = pt2.X - pt0.X;
double mb_y = pt2.Y - pt0.Y;
double k = (ma_x * mb_y - mb_x * ma_y);
if (k != 0)
{
k = (k / Math.Sqrt(k * k));
}
else
{
k = 1;
}
double v1 = (ma_x * mb_x) + (ma_y * mb_y);
double ma_val = Math.Sqrt(ma_x * ma_x + ma_y * ma_y);
double mb_val = Math.Sqrt(mb_x * mb_x + mb_y * mb_y);
double cosM = v1 / (ma_val * mb_val);
return (float)(Math.Acos(cosM) * 180 / Math.PI * k);
}
/// <summary>
/// 计算2点之间的角度
/// </summary>
/// <param name="pt1"></param>
/// <param name="pt2"></param>
/// <returns></returns>
public static double getAngle(Point pt1, Point pt2)
{
double mb_x = pt2.X - pt1.X;
double mb_y = pt2.Y - pt1.Y;
double rotation = Math.Atan2(mb_y, mb_x);
rotation = rotation / Math.PI * 180;
return rotation;
//double angle = 360 - rotation + 90;
//angle = angle < 0 ? 360 + angle : angle;
//angle = angle % 360;
//return Math.Floor(angle / 360 * 24);
}
/// <summary>
/// 计算2点之间的距离
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
public static double distance(Point p1, Point p2)
{
double result;
result = Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
return result;
}
/// <summary>
/// 以中心点旋转Angle角度
/// </summary>
/// <param name="origin">中心点</param>
/// <param name="reRotate">待旋转的点</param>
/// <param name="angle">旋转角度, 逆时针</param>
public static Point PointRotate(Point origin, Point rePoint, double angle)
{
double x = (rePoint.X - origin.X) * Math.Cos(angle) - (rePoint.Y - origin.Y) * Math.Sin(angle) + origin.X;
double y = (rePoint.X - origin.X) * Math.Sin(angle) + (rePoint.Y - origin.Y) * Math.Cos(angle) + origin.Y;
//rePoint.X = x;
//rePoint.Y = y;
return new Point((int)x, (int)y);
}
/// <summary>
/// 以指定点为中心,测算指定角度,指定长度位置的点
/// </summary>
/// <param name="p1">原点</param>
/// <param name="angle">角度</param>
/// <param name="distance">距离</param>
/// <returns></returns>
public static Point PointWithAngle(Point p1, double angle, double distance) {
var x2 = p1.X + distance * Math.Cos(angle / 180 * Math.PI);
var y2 = p1.Y + distance * Math.Sin(angle / 180 * Math.PI);
return new Point((int)x2, (int)y2);
}
/// <summary>
/// 找到无标签角度
/// </summary>
/// <param name="codeInfos"></param>
/// <param name="org"></param>
/// <param name="widthOffset"></param>
/// <param name="labelAngle"></param>
/// <returns></returns>
public static Point CalcLabelPoint(List<CodeInfo> codeInfos, Point org,int widthOffset,out int labelAngle) {
//Point Right_Batch_Point = new Point(RobotManage.Config.Right_Batch_X, RobotManage.Config.Right_Batch_Y);
Point Right_Batch_Point = org;
List<int> angles = new List<int>();
codeInfos.ForEach((c) => {
//Point op = Common.PointRotate(Right_Batch_Point, new Point(c.X, c.Y), 83d / 180 * Math.PI);
//c.X = op.X;
//c.Y = op.Y;
Point op = new Point(c.X, c.Y);
var a = (int)getAngle(Right_Batch_Point, op);
a += ConfigHelper.Config.Get<int>("AngleChange");
a = a < 0 ? 360 + a : a;
angles.Add(a);
});
angles.Sort();
//if (angles.Count > 1) {
angles.Add(360 + angles[0]);
//}
int biglen = 0;
int bigangles = 0;
for (int i = 0; i < angles.Count; i++) {
if (angles.Count() - i < 2)
break;
var x = angles[i+1] - angles[i];
if (x > biglen)
{
biglen = x;
bigangles = angles[i];
}
}
labelAngle = bigangles + biglen / 2;
labelAngle = labelAngle > 360 ? 360 - labelAngle : labelAngle;
var p2 = PointWithAngle(org, labelAngle, widthOffset);
return p2;
}
}
public class Msg
{
public string msgtxt;
public MsgLevel msgLevel;
public DateTime datetime;
}
/*
public class Msg
{
public static List<Msg> msg = new List<Msg>();
public string msgtxt;
public MsgLevel msgLevel;
public DateTime datetime;
public static List<Msg> get() {
if (_setlogones) {
_setlogones = false;
foreach (var m in msg)
LogUtil.info(m.msgtxt);
}
List<Msg> mm = new List<Msg>(msg);
return mm;
}
public static void add(string m, MsgLevel ml)
{
msg.Add(new Msg { msgtxt = m, msgLevel = ml, datetime=DateTime.Now });
}
static bool _setlogones = false;
internal static void setlogones()
{
_setlogones = true;
}
public static void clear()
{
msg.Clear();
}
}*/
public enum MsgLevel {
warning,
info
}
}
此文件类型无法预览
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!