Commit 0b9c6bfc 贾鹏旭

1.合并

2 个父辈 b905d7d3 abf7198d
......@@ -80,9 +80,6 @@
<Compile Include="util\JsonHelper.cs" />
<Compile Include="logs\LogUtil.cs" />
<Compile Include="util\LedUtil.cs" />
<Compile Include="util\MyWebClient.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="util\ProcessPictures.cs" />
<Compile Include="util\TcpClient.cs" />
<Compile Include="util\TcpServer.cs" />
......
......@@ -59,6 +59,9 @@
<HintPath>..\packages\MetroFramework-1.3.0.0.1.3.0.0\lib\MetroFramework.Fonts.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite, Version=1.0.113.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
......@@ -117,6 +120,10 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="manager\AlarmType.cs" />
<Compile Include="manager\BoardManager.cs" />
<Compile Include="smf\MyWebClient.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="smf\ServerCommunication.cs" />
<Compile Include="SQLite.cs" />
</ItemGroup>
<ItemGroup>
......
......@@ -6,6 +6,10 @@
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.12.0" newVersion="2.0.12.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
......@@ -25,7 +25,7 @@ namespace TSA_V.DeviceLibrary
public static bool DisableSideCylinder = false;
public static bool DisableBottomCylinder = false;
public static ServerCommunication serverCommunication = null;
private static string warnMsg = "";
public static string WarnMsg
{
......@@ -135,6 +135,8 @@ namespace TSA_V.DeviceLibrary
}
});
AlarmProcess.Init();
serverCommunication = new ServerCommunication();
serverCommunication.StartConnectServer();
return "";
}
......
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ExcelDataReader" version="3.6.0" targetFramework="net48" />
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net48" />
<package id="Stub.System.Data.SQLite.Core.NetFramework" version="1.0.113.3" targetFramework="net461" />
<package id="System.Data.SQLite.Core" version="1.0.113.7" targetFramework="net461" />
<package id="System.Net.Http" version="4.3.4" targetFramework="net461" />
......
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Windows;
public static class Http
{
public static string PostJson<T>(string url, Dictionary<string, string> headers, T jsonobject, int timeout = 10000, bool wlog=true)
{
RestClient client = new RestClient(url) { Timeout = timeout };
client.UseSerializer(new CustSerialize());
RestRequest request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
if (headers != null)
{
foreach (var head in headers)
{
request.AddHeader(head.Key, head.Value);
}
}
request.AddJsonBody(jsonobject);
IRestResponse response = client.Execute(request);
string s = response.Content;
//if (wlog)
// LogNet.log.Info("Return:" + s);
return s;
}
}
public class CustSerialize : RestSharp.Serialization.IRestSerializer
{
public string ContentType { get; set; } = "application/json";
public string[] SupportedContentTypes { get; set; } = new string[] { "application/json" };
public DataFormat DataFormat { get; set; } = DataFormat.Json;
public T Deserialize<T>(IRestResponse response)
{
return JsonConvert.DeserializeObject<T>(response.Content);
}
public string Serialize(object obj)
{
return JsonConvert.SerializeObject(obj);
}
public string Serialize(Parameter parameter)
{
return JsonConvert.SerializeObject(parameter.Value);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;
namespace TSA_V.Common
{
public class MyWebClient : WebClient
{
private int _timeout;
/// <summary>
/// 超时时间(毫秒)
/// </summary>
public int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
public MyWebClient()
{
this._timeout = 60000;
}
public MyWebClient(int timeout)
{
this._timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest result = (HttpWebRequest)base.GetWebRequest(address);
result.Timeout = this._timeout;
// result.KeepAlive = false;
result.ServicePoint.Expect100Continue = false;
return result;
}
}
public class HttpHelper
{
private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);
public static string PostJson(string url, Object operation, bool simulate = false)
{
try
{
if (operation == null)
{
return null;
}
try
{
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
string json = JsonHelper.SerializeObject(operation);
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.UTF8;
string result = wc.UploadString(url, "POST", json);
LogUtil.info("PostJson【" + url + "】发送【"+json+"】返回【"+result+"】");
if (!string.IsNullOrEmpty(result))
{
return result;
}
}
catch (WebException ex)
{
LogUtil.error("POST [" + url + "] WebException :" + ex.ToString(), 101);
}
catch (Exception e)
{
LogUtil.error("POST [" + url + "] ERROR:" + e.ToString(), 101);
}
}
catch (Exception ex)
{
LogUtil.error("Post ["+ url + "] 出错:" + ex);
}
return null;
}
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(timeOut))
{
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() + "\r\n" + url, 101);
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding)
{
try
{
LogUtil.info("HTTP GET FROM: " + url);
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
LogUtil.info("receive << " + result);
return result;
}
}
catch (Exception e)
{
LogUtil.error("HTTP GET ERROR:" + e.Message, 102);
}
return "";
}
public static Operation Post(string url, Operation operation, int timeout = 5000, bool printlog = false)
{
try
{
string json = JsonHelper.SerializeObject(operation);
string result = Post(url, json, timeout);
Operation op = JsonHelper.DeserializeJsonToObject<Operation>(result);
if (printlog)
{
LogUtil.info("Send [" + json + "] Revice [" + result + "]");
}
return op;
}
catch (Exception ex)
{
LogUtil.error("Post 出错【" + JsonHelper.SerializeObject(operation) + "】:" + ex);
}
return null;
}
}
}

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TSA_V.Common;
using TSA_V.DeviceLibrary;
public class ServerCommunication : IDisposable
{
const string ModuleType = "NEOSTATION";
const string DefaultCid = "NEOSTATION001";
public Status status = Status.Online;
static string server;
static string CID;
List<EquipMsg> msgList = new List<EquipMsg>();
int StoreID = 1;
string StoreName = "";
string WarnMsg = "";
private System.Timers.Timer serverConnectTimer = new System.Timers.Timer();
object serverclock = new object();
public ServerCommunication()
{
//server = ConfigAppSettings.GetValue("SMF_Serverurl", "http://192.168.1.243/smf-core/");
server = ConfigAppSettings.GetValue("SMF_Serverurl", "http://localhost:8800/");
CID = ConfigAppSettings.GetValue("SMF_CID", DefaultCid);
if(String.IsNullOrEmpty(CID))
{
CID = DefaultCid;
}
readLazyData();
//Common.config.Save();
if (server.ToLower().StartsWith("http"))
{
serverConnectTimer.Interval = 1000;
serverConnectTimer.AutoReset = true;
serverConnectTimer.Enabled = true;
serverConnectTimer.Elapsed += ServerConnectTimer_Elapsed;
GC.KeepAlive(serverConnectTimer);
}
}
private void ServerConnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (!Monitor.TryEnter(serverConnectTimer))
return;
try
{
SendStatus();
}
catch
{
}
finally
{
Monitor.Exit(serverConnectTimer);
}
}
public void StartConnectServer()
{
serverConnectTimer.Enabled = true;
}
public void StopConnectServer()
{
serverConnectTimer.Enabled = false;
}
/// <summary>
/// 获取整个料仓的状态
/// </summary>
Operation getStatus()
{
//构建发送给服务器的对象
Operation Operation = new Operation();
Operation.cid = CID;
Operation.seq = nextSeq();
if(TSAVBean.IsInSuddenDown)
{
status = Status.SuddenStop;
}else if (TSAVBean.WarnMsg != "")
{
status = Status.Warning;
}
else
{
status = Status.Online;
}
Operation.status = status;
if (showMsglist.TryDequeue(out var msg))
{
Operation.msgList.Add(msg);
}
while (Datalist.TryDequeue(out var msg1))
{
Operation.msgList.Add(msg1);
}
return Operation;
}
private static string api_communication = "/service/equipment/communication"; //流水线状态通信接口
public static string GetPostApi()
{
var host = server;
if (!host.StartsWith("http://"))
{
host = "http://" + host;
}
if (!host.EndsWith("/"))
{
host = host + "/";
}
host = host.TrimEnd('/');
if (!Uri.TryCreate(host + api_communication, UriKind.Absolute, out Uri u))
{
throw new Exception("Smf服务器地址配置错误:" + host);
}
return u.ToString();
}
public void SendStatus()
{
if (!server.ToLower().StartsWith("http"))
return;
lock (serverclock)
{
DateTime time = DateTime.Now;
//构建发送给服务器的对象
Operation lineOperation = getStatus();
Operation resultOperation = HttpHelper.Post(GetPostApi(), lineOperation);
//Operation resultOperation = JsonConvert.DeserializeObject<Operation>(returntxt);
if (resultOperation == null)
{
lineOperation.msgList.ForEach(m =>
{
if (m.type == msgType.DATA)
{
backupdata(m);
LogUtil.info("Data发送到SMF失败:" + m.msg);
}
});
}
ResultProcess(resultOperation);
}
}
private static int seq = 1;
public static int nextSeq()
{
if (seq.Equals(Int32.MaxValue))
{
//LogNet.log.Info("seq当前值:" + seq + ",重置seq=0");
seq = 0;
}
Interlocked.Increment(ref seq);
return seq;
}
public void ShowMsg(string msg, int keepsec = 1, msgType _msgType = msgType.INFO)
{
while (showMsglist.TryDequeue(out _)) ;
var m = new EquipMsg();
m.module = ModuleType;
m.type = _msgType;
m.msg = msg;
for (int i = 0; i < keepsec; i++)
showMsglist.Enqueue(m);
}
public void SendData(object data)
{
if (!server.ToLower().StartsWith("http"))
return;
var m = new EquipMsg();
m.module = ModuleType;
m.type = msgType.DATA;
m.msg = JsonConvert.SerializeObject(data);
Datalist.Enqueue(m);
}
const string lazyuploaddatafile = "lazyuploaddata.txt";
void backupdata(EquipMsg msg)
{
File.AppendAllText(lazyuploaddatafile, msg.msg + "\r\n");
}
void readLazyData()
{
if (!File.Exists(lazyuploaddatafile))
return;
var list = File.ReadAllLines(lazyuploaddatafile).ToList();
list.ForEach(x => { SendData(x); });
File.Delete(lazyuploaddatafile);
}
ConcurrentQueue<EquipMsg> showMsglist = new ConcurrentQueue<EquipMsg>();
ConcurrentQueue<EquipMsg> Datalist = new ConcurrentQueue<EquipMsg>();
void ResultProcess(Operation resultOperation)
{
//发送状态信息到服务器
if (resultOperation == null)
{
//判断服务端是否返回出库操作
return;
}
}
public void Dispose()
{
while (Datalist.TryDequeue(out var msg))
{
backupdata(msg);
}
}
}
public class ResultData
{
//{"code":0,"msg":"ok","data":"7"}
public int code { get; set; }
public string msg { get; set; }
public Dictionary<string, string> data { get; set; }
}
/// <summary>
///1=设备联机(正常就绪)(入库后,BOX恢复原始状态)(出库后,移载装置恢复原始状态),
///2=急停,3=故障,4=警告,5=调试
/// 6=入库执行中,7=入仓完成,8=入仓失败
/// 9=出库执行,10=出仓完成,11=出库失败
/// </summary>
public enum Status
{
/// <summary>
/// 1=设备联机(正常就绪)(入库后,BOX恢复原始状态)(出库后,移载装置恢复原始状态),
/// </summary>
Online = 1,
/// <summary>
///2=急停中
/// </summary>
SuddenStop = 2,
/// <summary>
/// 3=故障中
/// </summary>
InTrouble = 3,
/// <summary>
/// 4=警告
/// </summary>
Warning = 4,
}
/// <summary>
/// 与服务器通信用对象
/// </summary>
public class Operation
{
public string cid;
public string type = "NEOSTATION"; //NEOSTATION
public Status status;
public int seq;
public int op;
public List<EquipMsg> msgList = new List<EquipMsg>();
}
public class EquipMsg {
public string module;
[JsonConverter(typeof(StringEnumConverter))]
public msgType type;
public string msgCode;
public string msg;
public List<string> msgParams = new List<string>();
}
public enum msgType
{
INFO,
WARING,
ERROR,
DATA
}
......@@ -122,6 +122,8 @@
<!--禁用底部气缸-->
<add key="DisableBottomCylinder" value="1" />
<add key="SMF_Serverurl" value ="http://localhost:8800/"/>
<add key="SMF_CID" value ="NEOSTATION001"/>
</appSettings>
<log4net>
<appender name="defaultAppender" type="log4net.Appender.RollingFileAppender">
......
......@@ -267,6 +267,8 @@ namespace TSA_V
}
//MetcalManager.ColseAllPort();
AccAOI.camera.CameraManager.CloseCamera();
TSAVBean.serverCommunication.StopConnectServer();
// PUSICANControl.Close();
}
......
......@@ -2294,7 +2294,7 @@
<value> Password </value>
</data>
<data name="权限" xml:space="preserve">
<value> Permission </value>
<value> Authority </value>
</data>
<data name="用户管理" xml:space="preserve">
<value> User Management </value>
......
......@@ -117,7 +117,6 @@
</Content>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
......
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.12.0" newVersion="2.0.12.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!