init commit
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
using Newtonsoft.Json;
|
||||
using SimpleCore.Library;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using StandardScene.Chained;
|
||||
|
||||
namespace StandardScene.Utils
|
||||
{
|
||||
public static class JsonParser
|
||||
{
|
||||
public static object fileSync = new object();
|
||||
|
||||
public static void WriteJsonFile(TransportDelivery obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (fileSync)
|
||||
File.WriteAllText($"log/tasklist/{obj.TaskId}.json",
|
||||
JsonConvert.SerializeObject(obj, Formatting.Indented));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Diagnosis.Log("write tasklist error" + ExceptionFormatter.FormatEx(e), "error", true);
|
||||
}
|
||||
}
|
||||
|
||||
public static string ReadJsonFile(string path)
|
||||
{
|
||||
lock (fileSync)
|
||||
{
|
||||
return File.ReadAllText(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Json->Object
|
||||
//DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ChainedDeliveryMission.Delivery));
|
||||
public static TransportDelivery Deserialize(string json)
|
||||
{
|
||||
TransportDelivery obj = new TransportDelivery();
|
||||
|
||||
using MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
JsonConvert.PopulateObject(json, obj);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace StandardScene.Utils
|
||||
{
|
||||
public static class JsonTool
|
||||
{
|
||||
private static readonly JsonSerializerSettings DefaultJsonSerializerSettings = new JsonSerializerSettings()
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver(),
|
||||
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
|
||||
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
|
||||
DateFormatString = "yyyy-MM-dd HH:mm:ss"
|
||||
};
|
||||
public static string ToJson(this object obj)
|
||||
{
|
||||
return JsonConvert.SerializeObject(obj, DefaultJsonSerializerSettings);
|
||||
}
|
||||
public static string ToJson(this object obj, JsonSerializerSettings jsonSerializerSettings)
|
||||
{
|
||||
return JsonConvert.SerializeObject(obj, jsonSerializerSettings);
|
||||
}
|
||||
public static T JsonTo<T>(this string Json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(Json);
|
||||
}
|
||||
public static object JsonToObject(this string Json)
|
||||
{
|
||||
return JsonConvert.DeserializeObject(Json);
|
||||
}
|
||||
public static JObject JsonToJObject(this string Json)
|
||||
{
|
||||
return JObject.Parse(Json);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.IO.Ports;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using EasyModbus;
|
||||
|
||||
namespace StandardScene.Utils
|
||||
{
|
||||
|
||||
public class ModbusRtu
|
||||
{
|
||||
|
||||
public bool IsDebug { get; set; }
|
||||
public byte[] ReceiveAfterSend;
|
||||
public ModbusClient modbusRtu;
|
||||
//modbusRtu
|
||||
public void StartRtu(string com, int baudRate, Parity parity = Parity.None, StopBits stopBits = StopBits.One, int timeOut = 500)
|
||||
{
|
||||
modbusRtu = new ModbusClient(com);
|
||||
modbusRtu.Baudrate = baudRate;
|
||||
modbusRtu.Parity = parity;
|
||||
modbusRtu.StopBits = stopBits;
|
||||
modbusRtu.ConnectionTimeout = timeOut;
|
||||
modbusRtu.Connect();
|
||||
}
|
||||
//modbusTcp
|
||||
public void StartTcpRtu(string ip, int port)
|
||||
{
|
||||
modbusRtu = new ModbusClient(ip, port);
|
||||
modbusRtu.Connect(ip, port);
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
modbusRtu.Disconnect();
|
||||
}
|
||||
|
||||
#region ReadData
|
||||
public bool[] ReadCoilBuffer_01(byte slaveAddress, ushort startAddress, ushort numberOfPoints)//01 读取单个线圈
|
||||
{
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
var data = modbusRtu.ReadCoils(startAddress, numberOfPoints);
|
||||
return data;
|
||||
}
|
||||
public bool[] ReadDiscreteInputs_02(byte slaveAddress, ushort startAddress, ushort numberOfPoints)//02 读取输入线圈/离散量线圈
|
||||
{
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
var data = modbusRtu.ReadDiscreteInputs(startAddress, numberOfPoints);
|
||||
return data;
|
||||
}
|
||||
public int[] ReadRegisterBuffer_03(byte slaveAddress, ushort startAddress, ushort numberOfPoints)//03 读取保持寄存器
|
||||
{
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
var data = modbusRtu.ReadHoldingRegisters(startAddress, numberOfPoints);
|
||||
|
||||
return data;
|
||||
}
|
||||
public byte[] ReadRegisterBuffer_03_Byte(byte slaveAddress, ushort startAddress, ushort numberOfPoints)//03 读取保持寄存器
|
||||
{
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
var data = modbusRtu.ReadHoldingRegisters(startAddress, numberOfPoints);
|
||||
byte[] values = new byte[] { };
|
||||
foreach (var buff in data)
|
||||
{
|
||||
values = values.Concat(BitConverter.GetBytes((Int16)buff).AsEnumerable().Reverse()).ToArray();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
|
||||
public byte[] ReadInputBuffer_04(byte slaveAddress, ushort startAddress, ushort numberOfPoints)//04 读取输入寄存器
|
||||
{
|
||||
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
var data = modbusRtu.ReadInputRegisters(startAddress, numberOfPoints);
|
||||
byte[] values = new byte[] { };
|
||||
foreach (var buff in data)
|
||||
{
|
||||
values = values.Concat(BitConverter.GetBytes((Int16)buff).AsEnumerable().Reverse()).ToArray();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Write
|
||||
public void WriteSingleCoil_05(byte slaveAddress, ushort startAddress, bool Buffer)//05 写单个线圈
|
||||
{
|
||||
ReceiveAfterSend = null;
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
modbusRtu.WriteSingleCoil(startAddress, Buffer);
|
||||
ReceiveAfterSend = modbusRtu.receiveData;
|
||||
}
|
||||
public void WriteSingleRegister_06(byte slaveAddress, ushort startAddress, int Buffer)//06 写单寄存器
|
||||
{
|
||||
ReceiveAfterSend = null;
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
modbusRtu.WriteSingleRegister(startAddress, Buffer);
|
||||
ReceiveAfterSend = modbusRtu.receiveData;
|
||||
}
|
||||
public void WriteMultipleCoils_15(byte slaveAddress, ushort startAddress, bool[] Buffer)//15写一组线圈
|
||||
{
|
||||
ReceiveAfterSend = null;
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
modbusRtu.WriteMultipleCoils(startAddress, Buffer);
|
||||
ReceiveAfterSend = modbusRtu.receiveData;
|
||||
}
|
||||
public void WriteMultipleRegisters_16(byte slaveAddress, ushort startAddress, int[] Buffers)//16 写一组保持寄存器
|
||||
{
|
||||
ReceiveAfterSend = null;
|
||||
modbusRtu.UnitIdentifier = slaveAddress;
|
||||
modbusRtu.WriteMultipleRegisters(startAddress, Buffers);
|
||||
ReceiveAfterSend = modbusRtu.receiveData;
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using SimpleCore.Library;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace StandardScene.Utils
|
||||
{
|
||||
public class WebAPIHelper
|
||||
{
|
||||
private static WebAPIHelper instance = null;
|
||||
|
||||
public static WebAPIHelper Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
return instance ?? (instance = new WebAPIHelper());
|
||||
}
|
||||
}
|
||||
|
||||
private ConcurrentDictionary<string, HttpClient> clientPool = new ConcurrentDictionary<string, HttpClient>();
|
||||
|
||||
private HttpClient getClient(string urlString)
|
||||
{
|
||||
var url = new Uri(urlString);
|
||||
var key = $"{url.Host}:{url.Port}";
|
||||
return clientPool.GetOrAdd(key, _ => createClient());
|
||||
}
|
||||
|
||||
private HttpClient createClient()
|
||||
{
|
||||
var client = new HttpClient();
|
||||
client.Timeout = TimeSpan.FromSeconds(3);
|
||||
try
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("User-Agent", "MDS/1.1");
|
||||
client.DefaultRequestHeaders.Add("Accept", "*/*");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Diagnosis.Log($"fail to add http client default header:{e}", "task", true);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<string> GetStringAsync(string url)
|
||||
{
|
||||
return await getClient(url).GetStringAsync(url);
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 读取HTTP Get响应包文。
|
||||
// /// </summary>
|
||||
// /// <typeparam name="T">返回结果的类型</typeparam>
|
||||
// /// <param name="uriString">资源地址</param>
|
||||
// /// <param name="headers">可选的HTTP头列表</param>
|
||||
// /// <returns>响应结果</returns>
|
||||
// public async Task<T> GetAsync<T>(string uriString, Dictionary<string, string> headers = null)
|
||||
// {
|
||||
// T retv = default;
|
||||
//
|
||||
// HttpClient hc = getClient(uriString);
|
||||
// var request = new HttpRequestMessage(HttpMethod.Get, uriString);
|
||||
// if (headers != null)
|
||||
// {
|
||||
// foreach (var key in headers.Keys)
|
||||
// {
|
||||
// request.Headers.Add(key, headers[key]);
|
||||
// }
|
||||
// }
|
||||
// var resp = await hc.SendAsync(request);
|
||||
// resp.EnsureSuccessStatusCode();
|
||||
//
|
||||
// var opt = new JsonSerializerOptions
|
||||
// {
|
||||
// PropertyNameCaseInsensitive = true
|
||||
// };
|
||||
// opt.Converters.Add(new MyDateTimeConverter());
|
||||
// var json = await resp.Content.ReadAsStringAsync();
|
||||
// retv = JsonSerializer.Deserialize<T>(json, opt);
|
||||
//
|
||||
// return retv;
|
||||
// }
|
||||
//
|
||||
// private static JsonSerializerOptions jsonOptions = new JsonSerializerOptions
|
||||
// {
|
||||
// PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
// WriteIndented = true
|
||||
// };
|
||||
|
||||
// /// <summary>
|
||||
// /// 读取HTTP POST结果。
|
||||
// /// </summary>
|
||||
// /// <typeparam name="T1">响应结果类型</typeparam>
|
||||
// /// <typeparam name="T2">POST对象类型</typeparam>
|
||||
// /// <param name="uriString">资源地址</param>
|
||||
// /// <param name="data">请求包文对象</param>
|
||||
// /// <param name="headers">可选HTTP头列表</param>
|
||||
// /// <param name="logging">是否写入日志,默认为真</param>
|
||||
// /// <returns>响应对象</returns>
|
||||
// public async Task<T1> PostAsync<T1, T2>(string uriString, T2 data, Dictionary<string, string> headers = null, bool logging = true)
|
||||
// {
|
||||
// //if (logging)
|
||||
// Diagnosis.Log($"post to {uriString}\n{JsonSerializer.Serialize(data)}", "task", true);
|
||||
// T1 retv = default;
|
||||
//
|
||||
// HttpClient hc = getClient(uriString);
|
||||
// var request = new HttpRequestMessage(HttpMethod.Post, uriString);
|
||||
// if (headers != null)
|
||||
// {
|
||||
// foreach (var key in headers.Keys)
|
||||
// {
|
||||
// request.Headers.Add(key, headers[key]);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// HttpContent content = new StringContent(JsonSerializer.Serialize(
|
||||
// data,
|
||||
// jsonOptions
|
||||
// ));
|
||||
// content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
||||
// request.Content = content;
|
||||
// var resp = await hc.SendAsync(request);
|
||||
// resp.EnsureSuccessStatusCode();
|
||||
// if (logging)
|
||||
// Diagnosis.Post(JsonSerializer.Serialize(resp));
|
||||
//
|
||||
// var opt = new JsonSerializerOptions
|
||||
// {
|
||||
// PropertyNameCaseInsensitive = true
|
||||
// };
|
||||
// opt.Converters.Add(new MyDateTimeConverter());
|
||||
// var json = await resp.Content.ReadAsStringAsync();
|
||||
// Diagnosis.Log($"got post response\n{json}", "task", true);
|
||||
//
|
||||
// if (resp.StatusCode != System.Net.HttpStatusCode.OK)
|
||||
// Diagnosis.Log($"post {uriString} return not ok\nStatusCode={resp.StatusCode.ToString()}\njson", "task", true);
|
||||
// retv = JsonSerializer.Deserialize<T1>(json, opt);
|
||||
//
|
||||
// return retv;
|
||||
// }
|
||||
}
|
||||
|
||||
// public class MyDateTimeConverter : JsonConverter<DateTime>
|
||||
// {
|
||||
// public override bool CanConvert(Type typeToConvert)
|
||||
// {
|
||||
// return typeToConvert == typeof(DateTime);
|
||||
// }
|
||||
//
|
||||
// public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
// {
|
||||
// return DateTime.ParseExact(reader.GetString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
|
||||
// }
|
||||
//
|
||||
// public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
|
||||
// {
|
||||
// writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
// }
|
||||
// }
|
||||
}
|
||||
Reference in New Issue
Block a user