Ver código fonte

Add MockData

Yue 2 anos atrás
pai
commit
39042d6ba1

+ 3 - 0
.gitignore

@@ -55,6 +55,9 @@ build/
 
 ### VS  ###
 .vs/
+bin/
+obj/
+
 
 ### auto-import ###
 /UI/**/vite/auto-import/*.d.ts

+ 79 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Common/FileHelper.cs

@@ -0,0 +1,79 @@
+using System.Text;
+
+using Newtonsoft.Json;
+
+namespace Vbdsm.Common
+{
+    public class FileHelper
+    {
+        public static T? ReadFileInfo<T>(string fileName) where T : new()
+        {
+            var str = ReadFileInfo(fileName);
+            return Str2Obj<T>(str);
+        }
+
+        public static string ReadFileInfo(string fileName, string path = "Data")
+        {
+            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{path}\\{fileName}.json");
+            StringBuilder sb = new StringBuilder();
+            if (File.Exists(filePath)) //文件存在
+            {
+                try
+                {
+                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
+                    StreamReader reader = new StreamReader(fs, Encoding.UTF8);
+                    while (reader.ReadLine() is { } line)
+                    {
+                        sb.Append(line);
+                    }
+                    reader.Close();
+                    fs.Close();
+                }
+                catch
+                {
+                    // ignored
+                }
+            }
+
+            return sb.ToString();
+        }
+
+        public static void SaveFileInfo(object obj, string fileName)
+        {
+            string str = Obj2Str(obj);
+            SaveFileInfo(str, fileName);
+        }
+
+        public static void SaveFileInfo(string contents, string fileName)
+        {
+            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Data");
+            if (!Directory.Exists(path))
+            {
+                Directory.CreateDirectory(path);
+            }
+            string filePath = $"{path}\\{fileName}.json";
+            File.WriteAllText(filePath, contents);
+        }
+
+        public static T? Str2Obj<T>(string str) where T : new()
+        {
+            if (!string.IsNullOrEmpty(str))
+            {
+                try
+                {
+                    return JsonConvert.DeserializeObject<T>(str);
+                }
+                catch //(Exception e)
+                {
+                    return default;
+                }
+            }
+            return default;
+        }
+
+        public static string Obj2Str(object obj)
+        {
+            return JsonConvert.SerializeObject(obj, Formatting.Indented);
+        }
+    }
+}

+ 104 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Common/StrHexHelper.cs

@@ -0,0 +1,104 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace StressClient.Common
+{
+    public class StrHexHelper
+    {
+        // 字符串转16进制字符串   AB-->4142
+        public static string StrToHexStr(string str, Encoding encode)
+        {
+            byte[] b = encode.GetBytes(str);
+
+            string result = string.Empty;
+            foreach (var t in b)
+            {
+                result += Convert.ToString(t, 16);
+            }
+            return result;
+        }
+
+        // 将16进制字符串转换到byte[]
+        public static byte[] HexStrToArray(string str)
+        {
+            int count = str.Length / 2;
+            byte[] b = new byte[count];
+            for (int i = 0; i < count; i++)
+            {
+                string val = "0x" + str.Substring(i * 2, 2);
+                b[i] = Convert.ToByte(val, 16);    // '0x41'->65
+            }
+            return b;
+        }
+
+        public static string do_CRC(byte[] data)
+        {
+            uint crc = 0xFFFF;
+
+            foreach (var pos in data)
+            {
+                crc = (crc >> 8) ^ pos;
+                for (int i = 0; i < 8; i++)
+                {
+                    var check = (byte)(crc & 0x0001);
+                    crc >>= 1;
+                    if (check == 0x0001)
+                        crc ^= 0xA001;
+                }
+            }
+
+            //string ret_str = Convert.ToString(crc, 16);
+            string ret_str = crc.ToString("X4"); ;
+            return ret_str.ToUpper();
+        }
+
+        public static string do_CRC16(byte[] data)
+        {
+            byte[] returnVal = new byte[2];
+            byte CRC16Lo, CRC16Hi, CL, CH, SaveHi, SaveLo;
+            int i, Flag;
+            CRC16Lo = 0xFF;
+            CRC16Hi = 0xFF;
+            CL = 0x86;
+            CH = 0x68;
+            for (i = 0; i < data.Length; i++)
+            {
+                CRC16Lo = (byte)(CRC16Lo ^ data[i]);//每一个数据与CRC寄存器进行异或
+                for (Flag = 0; Flag <= 7; Flag++)
+                {
+                    SaveHi = CRC16Hi;
+                    SaveLo = CRC16Lo;
+                    CRC16Hi = (byte)(CRC16Hi >> 1);//高位右移一位
+                    CRC16Lo = (byte)(CRC16Lo >> 1);//低位右移一位
+                    if ((SaveHi & 0x01) == 0x01)//如果高位字节最后一位为
+                    {
+                        CRC16Lo = (byte)(CRC16Lo | 0x80);//则低位字节右移后前面补 否则自动补0
+                    }
+                    if ((SaveLo & 0x01) == 0x01)//如果LSB为1,则与多项式码进行异或
+                    {
+                        CRC16Hi = (byte)(CRC16Hi ^ CH);
+                        CRC16Lo = (byte)(CRC16Lo ^ CL);
+                    }
+                }
+            }
+            returnVal[0] = CRC16Hi;//CRC高位
+            returnVal[1] = CRC16Lo;//CRC低位
+            return Encoding.UTF8.GetString(returnVal);
+        }
+    }
+
+    public class Helper
+    {
+        public static decimal GetRan(int val, int diff, decimal k = 1)
+        {
+            if (k <= 0)
+                return 0;
+            System.Threading.Thread.Sleep(new Random().Next(10, 30));
+            var ran = Convert.ToDecimal(new Random(DateTime.Now.Millisecond).Next(val - diff, val + diff)) / k;
+            return ran;
+        }
+    }
+}

+ 67 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Gen/GenData.cs

@@ -0,0 +1,67 @@
+using System.Text;
+
+using StressClient.Common;
+
+using Vbdsm.Common;
+using Vbdsm.Model;
+
+namespace Vbdsm.Gen
+{
+    public class GenData
+    {
+        public GenData(string terminalIds, string? companyId)
+        {
+            TerminalIds = terminalIds;
+            CompanyId = companyId;
+        }
+
+        public string TerminalIds { get; set; }
+        public string? CompanyId { get; set; }
+
+        public string GenTerminals(string? date = null)
+        {
+            date = date ?? $"{DateTime.Now:yyyyMMddHH}{(DateTime.Now.Minute - DateTime.Now.Minute % 15):D2}00";
+            var str = $"st=01;cn={CompanyId};datatime={date};cphh=&&";
+            var tidList = TerminalIds.Split(',');
+            foreach (var tid in tidList)
+            {
+                str += GenTerminal(tid) + "$";
+            }
+            str = str.TrimEnd('$');
+            Console.WriteLine($"\t {str}");
+            byte[] bytes = StrHexHelper.HexStrToArray(StrHexHelper.StrToHexStr(str, Encoding.Default));
+            var result = $"##{str.Length:D6}{str}{StrHexHelper.do_CRC(bytes)}\r\n";
+            return result;
+        }
+
+        private string GenTerminal(string terminalId)
+        {
+            string fileName = $"{CompanyId}@{terminalId}";
+            TerminalData terminalData = FileHelper.ReadFileInfo<TerminalData>(fileName) ?? new TerminalData(CompanyId, terminalId);
+            var str = $"tid={terminalId}";
+            var power = new PowerEnergy();
+            var dp = Helper.GetRan(22000, 3000, 100);
+            var de = Helper.GetRan(6600, 600, 100);
+            var pe = terminalData.GetCurMonthTotal_P() == 0 ? 0 : terminalData.GetCurMonthTotal_P() + dp;
+            var qe = terminalData.GetCurMonthTotal_E() == 0 ? 0 : terminalData.GetCurMonthTotal_E() + de;
+            var ps = terminalData.Total_P + dp;
+            var qs = terminalData.Total_E + de;
+            power.SetEngine(pe, qe, ps, ps);
+            terminalData.SetMouthTotal_P(pe == 0 ? (decimal)0.01 : pe).SetMouthTotal_E(qe == 0 ? (decimal)0.01 : qe).SetTotal_P(ps).SetTotal_E(qs).Save();
+            str += "&" + power.GetStr();
+            var hia = new Harmonic("a").SetI(power.ia);
+            str += "&" + hia.GetStr_I();
+            var hib = new Harmonic("b").SetI(power.ib);
+            str += "&" + hib.GetStr_I();
+            var hic = new Harmonic("c").SetI(power.ic);
+            str += "&" + hic.GetStr_I();
+            var hua = new Harmonic("a").SetU(power.ua);
+            str += "&" + hua.GetStr_U();
+            var hub = new Harmonic("b").SetU(power.ub);
+            str += "&" + hub.GetStr_U();
+            var huc = new Harmonic("c").SetU(power.uc);
+            str += "&" + huc.GetStr_U();
+            return str;
+        }
+    }
+}

+ 83 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Gen/TerminalData.cs

@@ -0,0 +1,83 @@
+using Vbdsm.Common;
+
+namespace Vbdsm.Gen
+{
+    public class TerminalData
+    {
+        public TerminalData()
+        {
+            CompanyId = "";
+            TerminalId = "";
+        }
+
+        public TerminalData(string? companyId, string terminalId)
+        {
+            CompanyId = companyId;
+            TerminalId = terminalId;
+        }
+
+        public string? CompanyId { get; set; }
+        public string TerminalId { get; set; }
+        public Dictionary<string, decimal> MonthTotal_P { get; set; } = new Dictionary<string, decimal>();
+        public decimal Total_P { get; set; }
+        public Dictionary<string, decimal> MonthTotal_E { get; set; } = new Dictionary<string, decimal>();
+        public decimal Total_E { get; set; }
+        private string Key => $"{DateTime.Now:yyyyMMdd}";
+
+        public decimal GetCurMonthTotal_P()
+        {
+            if (!MonthTotal_P.TryGetValue(Key, out var d))
+            {
+                d = 0;
+            }
+            return d;
+        }
+
+        public decimal GetCurMonthTotal_E()
+        {
+            if (!MonthTotal_E.TryGetValue(Key, out var d))
+            {
+                d = 0;
+            }
+            return d;
+        }
+
+        public TerminalData SetTotal_P(decimal d)
+        {
+            Total_P = d;
+            return this;
+        }
+
+        public TerminalData SetMouthTotal_P(decimal d)
+        {
+            if (MonthTotal_P.ContainsKey(Key))
+            {
+                MonthTotal_P.Remove(Key);
+            }
+            MonthTotal_P.Add(Key, d);
+            return this;
+        }
+
+        public TerminalData SetTotal_E(decimal d)
+        {
+            Total_E = d;
+            return this;
+        }
+
+        public TerminalData SetMouthTotal_E(decimal d)
+        {
+            if (MonthTotal_E.ContainsKey(Key))
+            {
+                MonthTotal_E.Remove(Key);
+            }
+            MonthTotal_E.Add(Key, d);
+            return this;
+        }
+
+        public TerminalData Save()
+        {
+            FileHelper.SaveFileInfo(this, $"{CompanyId}@{TerminalId}");
+            return this;
+        }
+    }
+}

+ 70 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Model/Harmonic.cs

@@ -0,0 +1,70 @@
+using StressClient.Common;
+
+namespace Vbdsm.Model
+{
+    public class Harmonic
+    {
+        public Harmonic(string type)
+        {
+            this.type = type;
+        }
+
+        public Harmonic()
+        {
+            type = "";
+        }
+
+        public string type { get; set; }
+        public decimal h3 => GetVal();
+        public decimal h5 => GetVal();
+        public decimal h7 => GetVal();
+        public decimal h9 => GetVal();
+        public decimal h11 => GetVal();
+        public decimal h13 => GetVal();
+        public decimal h15 => GetVal();
+        public decimal h17 => GetVal();
+        public decimal h19 => GetVal();
+        public decimal h21 => GetVal();
+        public decimal h23 => GetVal();
+        public decimal h25 => GetVal();
+        public decimal h27 => GetVal();
+        public decimal h29 => GetVal();
+        public decimal h31 => GetVal();
+        public decimal hall => Helper.GetRan(550, 100, 100);
+        public decimal baseI { get; private set; }
+        public decimal baseU { get; private set; }
+
+        private decimal GetVal()
+        {
+            return new Random().Next(0, 100) > 50 ? Helper.GetRan(150, 50, 100) : 0;
+        }
+
+        private string GetStr()
+        {
+            return
+                $"h3:{h3},h5:{h5},h7:{h7},h9:{h9},h11:{h11},h13:{h13},h15:{h15},h17:{h17},h19:{h19},h21:{h21},h23:{h23},h25:{h25},h27:{h27},h29:{h29},h31:{h31},hall:{hall}";
+        }
+
+        public string GetStr_I()
+        {
+            return $"hi{type}={GetStr()},basei:{baseI}";
+        }
+
+        public string GetStr_U()
+        {
+            return $"hu{type}={GetStr()},baseu:{baseU}";
+        }
+
+        public Harmonic SetU(decimal u)
+        {
+            baseU = u;
+            return this;
+        }
+
+        public Harmonic SetI(decimal i)
+        {
+            baseI = i;
+            return this;
+        }
+    }
+}

+ 185 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Model/PowerEnergy.cs

@@ -0,0 +1,185 @@
+using StressClient.Common;
+
+namespace Vbdsm.Model
+{
+    public class PowerEnergy
+    {
+        public PowerEnergy()
+        {
+            var list_i = GetI();
+            ia = list_i[0];
+            ib = list_i[1];
+            ic = list_i[2];
+            var listU_220 = GetU_220();
+            ua = listU_220[0];
+            ub = listU_220[1];
+            uc = listU_220[2];
+            var listU_380 = GetU_380();
+            uab = listU_380[0];
+            ubc = listU_380[1];
+            uca = listU_380[2];
+            var listPf = GetPf();
+            pfa = listPf[0];
+            pfb = listPf[1];
+            pfc = listPf[2];
+
+            f = Helper.GetRan(5000, 20, 100);
+        }
+
+        public decimal pa => Math.Floor(ia * ua * pfa) / 1000;
+        public decimal pb => Math.Floor(ib * ub * pfb) / 1000;
+        public decimal pc => Math.Floor(ic * uc * pfc) / 1000;
+        public decimal p => pa + pb + pc;
+        public decimal qa => Math.Floor(ia * ua * (1 - pfa)) / 1000;
+        public decimal qb => Math.Floor(ib * ub * (1 - pfb)) / 1000;
+        public decimal qc => Math.Floor(ic * uc * (1 - pfc)) / 1000;
+        public decimal q => qa + qb + qc;
+        public decimal pfa { get; }
+        public decimal pfb { get; }
+        public decimal pfc { get; }
+        public decimal pf => Math.Floor(p * 100 / (ia * ua / 1000 + ib * ub / 1000 + ic * uc / 1000)) / 100;
+        public decimal ia { get; }
+        public decimal ib { get; }
+        public decimal ic { get; }
+        public decimal iz => Helper.GetRan(1100, 100, 10);
+        public decimal ua { get; }
+        public decimal ub { get; }
+        public decimal uc { get; }
+        public decimal uab { get; }
+        public decimal ubc { get; }
+        public decimal uca { get; }
+
+        //需量负荷
+        public decimal dp => Helper.GetRan((int)Math.Floor(p * 1000), 500, 1000);
+
+        //负荷率
+        public decimal pv => Helper.GetRan(8500, 1500, 100);
+
+        public decimal tpe { get; set; }
+        public decimal tqe { get; set; }
+        public decimal fpe { get; set; }
+        public decimal fqe { get; set; }
+        public decimal tps { get; set; }
+        public decimal tqs { get; set; }
+        public decimal fps { get; set; }
+        public decimal fqs { get; set; }
+        public decimal uaw => GetUw(ua, 220);
+        public decimal ubw => GetUw(ub, 220);
+        public decimal ucw => GetUw(uc, 220);
+        public decimal uabw => GetUw(uab, 380);
+        public decimal ubcw => GetUw(ubc, 380);
+        public decimal ucaw => GetUw(uca, 380);
+        public decimal fw => f - 50;
+        public decimal f { get; }
+        public decimal inbalance => GetUnbalance_I();
+        public decimal unbalance => GetUnbalance_U();
+        public decimal t => Helper.GetRan(42, 3);
+        public decimal t2 { get; set; }
+        public decimal t3 { get; set; }
+        public decimal t4 { get; set; }
+        public decimal t5 { get; set; }
+        public decimal t6 { get; set; }
+        public decimal t7 { get; set; }
+        public decimal t8 { get; set; }
+
+        public PowerEnergy SetEngine(decimal pe, decimal qe, decimal ps, decimal qs)
+        {
+            tpe = pe;
+            tqe = qe;
+            fpe = 0;
+            fqe = 0;
+            tps = ps;
+            tqs = qs;
+            fps = 0;
+            fqs = 0;
+            return this;
+        }
+
+        private List<decimal> GetU_220()
+        {
+            var ran = new Random().Next(2303, 2308);
+            var list = new List<decimal>
+            {
+                Helper.GetRan(ran * 10, 150, 100),
+                Helper.GetRan(ran * 10, 250, 100),
+                Helper.GetRan(ran * 10, 150, 100)
+            };
+            return list;
+        }
+
+        private List<decimal> GetU_380()
+        {
+            var ran = new Random().Next(4003, 4008);
+            var list = new List<decimal>
+            {
+                Helper.GetRan(ran * 10, 150, 100),
+                Helper.GetRan(ran * 10, 250, 100),
+                Helper.GetRan(ran * 10, 150, 100)
+            };
+            return list;
+        }
+
+        private List<decimal> GetI()
+        {
+            var ran = new Random().Next(1000, 1200);
+            var list = new List<decimal>
+            {
+                Helper.GetRan(ran * 100, 450, 100),
+                Helper.GetRan(ran * 100, 350, 100),
+                Helper.GetRan(ran * 100, 550, 100)
+            };
+            return list;
+        }
+
+        public decimal GetUw(decimal u, decimal un)
+        {
+            var w = (u - un) * 100 / un;
+            w = Math.Floor(w * 100) / 100;
+            return w;
+        }
+
+        private List<decimal> GetPf()
+        {
+            var ran = new Random().Next(955, 965);
+            var list = new List<decimal>
+            {
+                Helper.GetRan(ran * 10, 50, 10000),
+                Helper.GetRan(ran * 10, 50, 10000),
+                Helper.GetRan(ran * 10, 50, 10000)
+            };
+            return list;
+        }
+
+        private decimal GetUnbalance_I()
+        {
+            var arr = new decimal[3];
+            arr[0] = ia;
+            arr[1] = ib;
+            arr[2] = ic;
+            var max = arr.Max();
+            var min = arr.Min();
+            var i = (max - min) * 100 / max;
+            i = Math.Floor(i * 100) / 100;
+            return i;
+        }
+
+        private decimal GetUnbalance_U()
+        {
+            var arr = new decimal[3];
+            arr[0] = ua;
+            arr[1] = ub;
+            arr[2] = uc;
+            var max = arr.Max();
+            var ave = arr.Average();
+            var u = (max - ave) * 100 / ave;
+            u = Math.Floor(u * 100) / 100;
+            return u;
+        }
+
+        public string GetStr()
+        {
+            var str = $"p={p}&pa={pa}&pb={pb}&pc={pc}&q={q}&qa={qa}&qb={qb}&qc={qc}&pf={pf}&pfa={pfa}&pfb={pfb}&pfc={pfc}&ia={ia}&ib={ib}&ic={ic}&iz={iz}&ua={ua}&ub={ub}&uc={uc}&uab={uab}&ubc={ubc}&uca={uca}&dp={dp}&pv={pv}&uaw={uaw}&ubw={ubw}&ucw={ucw}&uabw={uabw}&ubcw={ubcw}&ucaw={ucaw}&f={f}&fw={fw}&inbalance={inbalance}&unbalance={unbalance}&t={t}&t2={t2}&t3={t3}&t4={t4}&t5={t5}&t6={t6}&t7={t7}&t8={t8}&tps={tps}&tqs={tqs}&fps={fps}&fqs={fqs}&tpe={tpe}&tqe={tqe}&fpe={fpe}&fqe={fqe}";
+            return str;
+        }
+    }
+}

+ 43 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Program.cs

@@ -0,0 +1,43 @@
+using Vbdsm.Settings;
+using Vbdsm.SocketClients;
+
+Console.WriteLine("------------------------数据上传(模拟)程序启动------------------------");
+CancellationTokenSource tokenSource = new CancellationTokenSource();
+CancellationToken cancellationToken = tokenSource.Token;
+var clients = new Dictionary<string?, TpcClient>();
+var terminals = new List<TerminalSetting>();
+if (AppSetting.Instance.Terminals.Count > 0)
+{
+    terminals.AddRange(AppSetting.Instance.Terminals);
+}
+foreach (var terminal in terminals)
+{
+    var client = new TpcClient(terminal.CompanyId, terminal.TerminalIds);
+    if (!clients.ContainsKey(terminal.CompanyId))
+    {
+        clients.Add(terminal.CompanyId, client);
+        Task.Run(() => client.Run(), cancellationToken);
+    }
+}
+Console.WriteLine("------------------------数据上传(模拟)启动完成------------------------");
+while (true)
+{
+    string? cmd = Console.ReadLine();
+    if (cmd == "exit")
+    {
+        break;
+    }
+
+    if (cmd != null)
+    {
+        if (clients.TryGetValue(cmd, out var _client))
+        {
+            _client.ReSend();
+        }
+        else
+        {
+            Console.WriteLine($"未能找到客户端【{cmd}】");
+        }
+    }
+}
+tokenSource.Cancel();

+ 33 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Settings/AppSetting.cs

@@ -0,0 +1,33 @@
+using System.Text;
+
+using Newtonsoft.Json;
+
+namespace Vbdsm.Settings
+{
+    public class AppSetting
+    {
+        public List<ServerSetting> Servers { get; set; } = new List<ServerSetting>();
+        public int MaxErrorCount { get; set; } = 10;
+        public bool UseInnerTerminal { get; set; } = false;
+        public List<TerminalSetting> Terminals { get; set; } = new List<TerminalSetting>();
+
+        private static AppSetting? _instance;
+        public static AppSetting Instance => GetInstance();
+
+        private static AppSetting GetInstance()
+        {
+            if (_instance == null)
+            {
+                using var fileStream = new FileStream("appsettings.json", FileMode.Open, FileAccess.Read);
+                int n = (int)fileStream.Length;
+                byte[] bt = new byte[n];
+                var read = fileStream.Read(bt, 0, n);
+                fileStream.Close();
+
+                string data = Encoding.UTF8.GetString(bt, 0, n);
+                _instance = JsonConvert.DeserializeObject<AppSetting>(data) ?? new AppSetting();
+            }
+            return _instance;
+        }
+    }
+}

+ 13 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Settings/ServerSetting.cs

@@ -0,0 +1,13 @@
+namespace Vbdsm.Settings;
+
+public class ServerSetting
+{
+    public ServerSetting(string ip, int port)
+    {
+        Ip = ip;
+        Port = port;
+    }
+
+    public string Ip { get; set; }
+    public int Port { get; set; }
+}

+ 14 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Settings/TerminalSetting.cs

@@ -0,0 +1,14 @@
+namespace Vbdsm.Settings
+{
+    public class TerminalSetting
+    {
+        public TerminalSetting(string? companyId, string terminalIds)
+        {
+            CompanyId = companyId;
+            TerminalIds = terminalIds;
+        }
+
+        public string? CompanyId { get; set; }
+        public string TerminalIds { get; set; }
+    }
+}

+ 188 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/SocketClients/TpcClient.cs

@@ -0,0 +1,188 @@
+using SuperSocket.ClientEngine;
+
+using System.Net;
+using System.Text;
+
+using Vbdsm.Gen;
+using Vbdsm.Settings;
+
+namespace Vbdsm.SocketClients
+{
+    public class TpcClient
+    {
+        private Dictionary<string, AsyncTcpSession> Clients { get; }
+
+        private int MaxErrorCount { get; }
+        private int MinuteInterval => 15;
+        private long LastRequestTime { get; set; }
+        private int ErrorCount { get; set; }
+
+        private string? ClientId { get; }
+        private string TerminalIds { get; }
+
+        public TpcClient(string? clientId, string terminalIds)
+        {
+            Clients = GenClients();
+
+            MaxErrorCount = AppSetting.Instance.MaxErrorCount;
+            ClientId = clientId;
+            TerminalIds = terminalIds;
+            LastRequestTime = CalcCurrentTime();
+        }
+
+        private Dictionary<string, AsyncTcpSession> GenClients()
+        {
+            var clients = new Dictionary<string, AsyncTcpSession>();
+            foreach (var server in AppSetting.Instance.Servers)
+            {
+                var key = $"{server.Ip}:{server.Port}";
+                if (!clients.ContainsKey(key))
+                {
+                    var client = InitClient(key);
+                    clients.Add(key, client);
+                }
+            }
+            return clients;
+        }
+
+        private AsyncTcpSession InitClient(string key, AsyncTcpSession? client = null)
+        {
+            if (client != null)
+                client.Close();
+            client = new AsyncTcpSession();
+            try
+            {
+                var arr = key.Split(':');
+                var ip = arr[0];
+                var port = arr[1];
+                if (arr.Length < 2)
+                {
+                    return client;
+                }
+
+                // 连接断开事件
+                client.Closed += (sender, _) =>
+                {
+                    client = sender as AsyncTcpSession;
+                    string message = $"[{DateTime.Now}] :客户端【{ClientId}】【{ip}:{port}】连接断开。";
+                    Console.WriteLine(message);
+                };
+                // 收到服务器数据事件
+                client.DataReceived += (_, e) =>
+                {
+                    string msg = Encoding.Default.GetString(e.Data, 0, e.Length).ToString().Replace("\r\n", "");
+                    string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】接受消息 => {msg}。";
+                    Console.WriteLine(message);
+                };
+                // 连接到服务器事件
+                client.Connected += (_, _) =>
+                {
+                    string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】连接成功。";
+                    Console.WriteLine(message);
+                };
+                // 发生错误的处理
+                client.Error += (_, e) =>
+                {
+                    string message = $"[{DateTime.Now}] 客户端【{ClientId}】【{ip}:{port}】错误 => {e.Exception.Message}";
+                    Console.WriteLine(message);
+                };
+
+                client.Connect(new IPEndPoint(IPAddress.Parse(ip), Convert.ToInt16(port)));
+            }
+            catch (Exception e)
+            {
+                Console.WriteLine(e.Message);
+            }
+            return client;
+        }
+
+        public void Run()
+        {
+            try
+            {
+                Console.WriteLine($"[{DateTime.Now}]  客户端【{ClientId}@{TerminalIds}】开始运行");
+                // 创建连接
+                Thread.Sleep(2000);
+                while (true)
+                {
+                    Console.Write(".");
+                    Send();
+                    Thread.Sleep(2 * 1000);
+                }
+            }
+            catch (Exception e)
+            {
+                Console.WriteLine(e.Message);
+            }
+        }
+
+        public void ReSend()
+        {
+            Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】 手动触发 ==>");
+            Send(false);
+        }
+
+        private void Send(bool needCheck = true)
+        {
+            if (ErrorCount >= MaxErrorCount || needCheck && !CheckSend())
+            {
+                return;
+            }
+
+            try
+            {
+                LastRequestTime = CalcCurrentTime();
+                Console.WriteLine($"\r\n[{DateTime.Now}] 客户端【{ClientId}】发送数据[{LastRequestTime}] ==>");
+                string str = new GenData(TerminalIds, ClientId).GenTerminals(LastRequestTime + "");
+                byte[] bytes = Encoding.UTF8.GetBytes(str);
+                foreach (var kv in Clients)
+                {
+                    ErrorCount = 0;
+                    Send(kv, bytes);
+                }
+            }
+            catch (Exception e)
+            {
+                ErrorCount++;
+                Console.WriteLine(e);
+            }
+        }
+
+        private void Send(KeyValuePair<string, AsyncTcpSession> keyValue, byte[] bytes)
+        {
+            var client = keyValue.Value;
+            if (client.IsConnected)
+            {
+                Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】发送数据");
+                client.Send(bytes, 0, bytes.Length);
+            }
+            else
+            {
+                client = InitClient(keyValue.Key, client);
+                Clients.Remove(keyValue.Key);
+                Clients.Add(keyValue.Key, client);
+                ErrorCount++;
+                Console.WriteLine($"[{DateTime.Now}] 客户端【{ClientId}】【{keyValue.Key}】连接失败 ==> {ErrorCount}/{MaxErrorCount}");
+                Thread.Sleep(2 * 1000);
+                if (ErrorCount <= MaxErrorCount)
+                {
+                    Send(keyValue, bytes);
+                }
+            }
+        }
+
+        private bool CheckSend()
+        {
+            var time = CalcCurrentTime() - LastRequestTime;
+            return time > 0;
+        }
+
+        private long CalcCurrentTime()
+        {
+            //long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHH}{(DateTime.Now.Minute - DateTime.Now.Minute % minuteInterval):D2}00");
+            long time = Convert.ToInt64($"{DateTime.Now:yyyyMMddHHmm00}");
+            time -= (time - (time / 10000) * 10000) % (MinuteInterval * 100);
+            return time;
+        }
+    }
+}

+ 22 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/Vbdsm.Hj212.csproj

@@ -0,0 +1,22 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <OutputType>Exe</OutputType>
+    <TargetFramework>net6.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+    <RootNamespace>Vbdsm</RootNamespace>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
+    <PackageReference Include="SuperSocket.ClientEngine.Core" Version="0.10.0" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <None Update="appsettings.json">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
+
+</Project>

+ 26 - 0
VB_DSM_DATA/VbdsmMockData/Vbdsm.Hj212/appsettings.json

@@ -0,0 +1,26 @@
+{
+  "Servers": [
+    {
+      "ip": "127.0.0.1",
+      "port": 7777
+    },
+    {
+      "ip": "47.112.30.247",
+      "port": 11112
+    }
+  ],
+  "maxErrorCount": 10, //客户端错误上线
+  //模拟的终端配置
+  "terminals": [
+    {
+      "CompanyId": "1",
+      "TerminalIds": "YD001_01,YD001_02"
+    }
+  ],
+  "work_day_time_span": [
+    "11:00",
+    "13:30",
+    "16:00",
+    "21:30"
+  ]
+}

+ 25 - 0
VB_DSM_DATA/VbdsmMockData/VbdsmMockData.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.4.33213.308
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Vbdsm.Hj212", "Vbdsm.Hj212\Vbdsm.Hj212.csproj", "{39F8F08C-0F9D-468E-A296-5BF3D0044BB6}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{39F8F08C-0F9D-468E-A296-5BF3D0044BB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{39F8F08C-0F9D-468E-A296-5BF3D0044BB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{39F8F08C-0F9D-468E-A296-5BF3D0044BB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{39F8F08C-0F9D-468E-A296-5BF3D0044BB6}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {9C219E8A-B739-4C47-A4E9-192248BC5DE1}
+	EndGlobalSection
+EndGlobal