using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Globalization; using System.IO; namespace ShowTrend3.Libs { public class NetClient { private readonly string ServerStr = "10.10.45.152"; private readonly int PortStr = 1070; private readonly IPEndPoint IpPoint; private enum Cmd { pasp_download = 4, history = 20, download_nh = 21, dir_browse = 23 } public NetClient() { IpPoint = new IPEndPoint(IPAddress.Parse(ServerStr), PortStr); } public Queue DirBrowse(string dir) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 5000, SendTimeout = 5000 }; try { //Connect socket.Connect(IpPoint); //SendRequest socket.Send(CreateCommand(Cmd.dir_browse, dir, 0).ToArray()); Queue result = new Queue(); //GetRequest byte mark; while (true) { mark = SocketReceiveByte(ref socket); if (mark == 0xff || mark == 0x00) break; if (mark == 0x01) { string r = SocketReceiveString(ref socket); if (r != "" || r != "." || r != "..") result.Enqueue(r); } } return result; } catch (Exception e) { Console.WriteLine(e.Message); return new Queue(); } finally { socket.Disconnect(false); } } public PasportVDP PaspDownload(string dir) { PasportVDP result = new PasportVDP(); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 5000, SendTimeout = 2000 }; try { //Connect socket.Connect(IpPoint); //SendRequest socket.Send(CreateCommand(Cmd.pasp_download, dir).ToArray()); //GetRequest1 if (SocketReceiveByte(ref socket) != 0x01) return result; byte[] t = SocketReceiveBytes(ref socket, 15); if (t.Length != 15) return result; //ConvertPasport1 result.NumberVDP = t[0]; result.TimeStart = new DateTime(t[1] + t[2] * 256, t[3], t[4], t[5], t[6], t[7]); result.TimeEnd = new DateTime(t[8] + t[9] * 256, t[10], t[11], t[12], t[13], t[14]); result.HaveDate = true; //GetRequest2 if (SocketReceiveByte(ref socket) != 0x01) return result; t = SocketReceiveBytes(ref socket, 1512); if (t.Length != 1512) return result; //ConvertPasport2 int caret = 0; result.KodNPlav = BitConverter.ToInt32(t, 0); caret += 4; result.NPlav = ConvertBytesToString(t, caret, 12); caret += 12; result.RM = ConvertBytesToString(t, caret, 11); caret += 11; result.Splav = ConvertBytesToString(t, caret, 101); caret += 101; result._is = ConvertBytesToString(t, caret, 51); caret += 51; result.Notd = BitConverter.ToUInt16(t, caret); caret += 2; result.VesSlit = BitConverter.ToUInt16(t, caret); caret += 2; result.Diam = BitConverter.ToUInt16(t, caret); caret += 2; result.PrPl = BitConverter.ToUInt16(t, caret); caret += 2; result.Tin = ConvertBytesToString(t, caret, 9); caret += 9; result.Dzap = ConvertBytesToString(t, caret, 9); caret += 9; result.Dlog = BitConverter.ToUInt16(t, caret); caret += 2; result.Last = BitConverter.ToUInt16(t, caret); caret += 2; result.Dlper = BitConverter.ToUInt16(t, caret); caret += 2; result.Nazn = ConvertBytesToString(t, caret, 51); caret += 51; result.Kompl = BitConverter.ToUInt16(t, caret); caret += 2; result.Izl = BitConverter.ToUInt16(t, caret); caret += 2; result.Robm = BitConverter.ToSingle(t, caret); caret += 4; result.Rizol = BitConverter.ToSingle(t, caret); caret += 4; result.Dkr = BitConverter.ToUInt16(t, caret); caret += 2; result.Nkon = ConvertBytesToString(t, caret, 51); caret += 51; result.Pos = ConvertBytesToString(t, caret, 6); caret += 6; result.Ukaz = ConvertBytesToString(t, caret, 51); caret += 51; result.Zakaz = ConvertBytesToString(t, caret, 51); caret += 51; result.Kat = ConvertBytesToString(t, caret, 51); caret += 51; result.Pril = ConvertBytesToString(t, caret, 3); caret += 3; result.Reserved = ConvertBytesToString(t, caret, 1023); caret += 1023; result.HavePasport = true; return result; } catch (Exception e) { Console.WriteLine(e.Message); return result; } finally { socket.Disconnect(false); } } public async Task> TechCycle(int VDP, DateTime TimeStart, DateTime TimeEnd) { SortedList result = new SortedList(); List>> tasks = new List>>(); try { //Check Params if (VDP < 0 || (VDP > 50 && VDP < 90) || VDP > 94) throw new Exception("Нет печи №" + VDP); if (TimeStart > TimeEnd) throw new Exception("Не верно задано время."); //PreStart DateTime tempDateTime = TimeStart; List requests = new List(); bool flag = false; while (!flag) { requests.Add( tempDateTime.Year.ToString() + tempDateTime.Month.ToString("D2") + tempDateTime.Day.ToString("D2") + "." + VDP.ToString("D2") + "3"); flag = (tempDateTime.Year >= TimeEnd.Year && tempDateTime.Month >= TimeEnd.Month && tempDateTime.Day >= TimeEnd.Day); tempDateTime = tempDateTime.AddDays(1); } //LoadAllList if (TimeStart <= DateTime.Now.AddDays(-9) && !await UploadArchiveToServer(VDP, 3, TimeStart, TimeEnd)) throw new Exception("Не загружен архив."); //SendRequests foreach (var e in requests) tasks.Add(DownloadAllPackage(CreateCommand(Cmd.download_nh, e).ToArray())); //ConvertResult foreach (var e in tasks) { e.Wait(); var r = e.Result; while (true) { if (r.Count == 0) break; string x = ""; while (r.Peek() != 0x09 && r.Peek() != 0x0a) x += ConvertByteToChar(r.Dequeue()); int value = int.Parse(x); r.Dequeue(); while (r.Peek() != 0x09 && r.Peek() != 0x0a) r.Dequeue(); r.Dequeue(); x = ""; while (r.Peek() != 0x09 && r.Peek() != 0x0a) x += ConvertByteToChar(r.Dequeue()); DateTime key = ConvertUnixTimeToDateTime(int.Parse(x)); r.Dequeue(); if (result.ContainsKey(key)) result[key] = value; else result.Add(key, value); } } return result; } catch (Exception e) { Console.WriteLine(e.Message); return new SortedList(); } } public async Task Analog(int VDP, DateTime TimeStart, DateTime TimeEnd, int[] listSignals) { Queue tasks = new Queue(); List requests = new List(); try { //Check Params if (VDP < 0 || (VDP > 50 && VDP < 90) || VDP > 94) throw new Exception("Нет печи №" + VDP); if (TimeStart > TimeEnd) throw new Exception("Не верно задано время."); //PreStart DateTime tempDateTime = TimeStart; bool flag = false; while (!flag) { requests.Add( tempDateTime.Year.ToString() + tempDateTime.Month.ToString("D2") + tempDateTime.Day.ToString("D2") + "." + VDP.ToString("D2") + "1"); flag = (tempDateTime.Year == TimeEnd.Year && tempDateTime.Month == TimeEnd.Month && tempDateTime.Day == TimeEnd.Day); tempDateTime = tempDateTime.AddDays(1); TempDir.LockRead(requests.Last()); } //Load All List if (TimeStart <= DateTime.Now.AddDays(-9) && !await UploadArchiveToServer(VDP, 1, TimeStart, TimeEnd)) throw new Exception("Не загружен архив."); //Send Requests foreach (var e in requests) tasks.Enqueue(DownloadAllPackage(e)); //Result AnalogSignals result = new AnalogSignals(VDP){ retAnalogs = listSignals}; double step = (VDP >= 0 && VDP <= 50) ? 0.5 : 1; for (int e = 0; e < requests.Count; e++) { await tasks.Dequeue(); Console.WriteLine("read_" + (e + 1) + ": " + DateTime.Now.ToLongTimeString()); double secondsCount = 0; List row = new List(); DateTime d = DateTime.ParseExact(requests[e].Substring(0, 8), "yyyyMMdd", CultureInfo.InvariantCulture).ToUniversalTime(); int tic = 60; while (!TempDir.CanRead(requests[e])) { await Task.Delay(1000); if (tic-- == 0) throw new Exception("Занят локальный архив: " + requests[e]); } using (FileStream r = TempDir.StartRead(requests[e])) { while (r.Position < r.Length) { var t = r.ReadByte(); switch (t) { case 0xfb: if (row.Count != 0 && d.AddSeconds((double)secondsCount) > TimeStart && d.AddSeconds((double)secondsCount) < TimeEnd) result.AddSignals(d.AddSeconds((double)secondsCount), row); secondsCount = step * BitConverter.ToInt32(new byte[] { (byte)r.ReadByte(), (byte)r.ReadByte(), (byte)r.ReadByte(), (byte)r.ReadByte() }, 0); break; case 0xfc: if (row.Count == 0) row.Add(null); if (d.AddSeconds((double)secondsCount) > TimeStart && d.AddSeconds((double)secondsCount) < TimeEnd) result.AddSignals(d.AddSeconds((double)secondsCount), row); for (var j = 0; j < row.Count; j++) row[j] = null; secondsCount = step * BitConverter.ToInt32(new byte[] { (byte)r.ReadByte(), (byte)r.ReadByte(), (byte)r.ReadByte(), (byte)r.ReadByte() }, 0); if (d.AddSeconds((double)secondsCount) > TimeStart && d.AddSeconds((double)secondsCount) < TimeEnd) result.AddSignals(d.AddSeconds((double)secondsCount), row); break; case 0xfe: if (row.Count != 0 && d.AddSeconds((double)secondsCount) > TimeStart && d.AddSeconds((double)secondsCount) < TimeEnd) result.AddSignals(d.AddSeconds((double)secondsCount), row); secondsCount += step * BitConverter.ToInt16(new byte[] { (byte)r.ReadByte(), (byte)r.ReadByte() }, 0); break; case 0xff: if (row.Count != 0 && d.AddSeconds((double)secondsCount) > TimeStart && d.AddSeconds((double)secondsCount) < TimeEnd) result.AddSignals(d.AddSeconds((double)secondsCount), row); secondsCount += step; break; default: while (row.Count <= t) row.Add(null); row[t] = (byte)r.ReadByte(); break; } } } } return result; } catch (Exception e) { Console.WriteLine(e.Message); return new AnalogSignals(VDP) { retAnalogs = listSignals }; } finally { foreach(var e in requests) TempDir.FreeRead(e); } } private Queue CreateCommand(Cmd cmd, string val, int dir = 0) { Queue q = new Queue(); foreach (var e in BitConverter.GetBytes((uint)cmd)) q.Enqueue(e); if (cmd == Cmd.dir_browse) q.Enqueue((byte)dir); foreach (var e in BitConverter.GetBytes((uint)val.Length)) q.Enqueue(e); foreach (var e in val) q.Enqueue((byte)e); q.Enqueue(0x00); return q; } private byte SocketReceiveByte(ref Socket socket) { try { byte[] t = new byte[1]; int countbyte = socket.Receive(t); if (countbyte != 1) throw new Exception("Ошибка получение Байта"); return t[0]; } catch (Exception e) { Console.WriteLine(e.Message); return 0xff; } } private bool SocketReceiveBytes(ref Socket socket, ref Queue q, int length) { try { while (length != 0) { byte[] b = new byte[length]; int countbytes = socket.Receive(b); for (int i = 0; i < countbytes; i++) q.Enqueue(b[i]); length -= countbytes; } return true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } private byte[] SocketReceiveBytes(ref Socket socket, int length) { List result = new List(); try { while (result.Count != length) { int count = length - result.Count; byte[] t = new byte[count]; int countbytes = socket.Receive(t); if (countbytes > 0) result.AddRange(t.Take(countbytes)); } return result.ToArray(); } catch (Exception e) { Console.WriteLine(e.Message); return new byte[0]; } } private string SocketReceiveString(ref Socket socket) { Queue q = new Queue(); if (SocketReceiveBytes(ref socket, ref q, (int)BitConverter.ToUInt32(SocketReceiveBytes(ref socket, 4), 0) + 1)) return ConvertBytesToString(ref q); return ""; } private async Task UploadArchiveToServer(int vdp, int type, DateTime tStart, DateTime tEnd) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 5000, SendTimeout = 5000 }; socket.Connect(IpPoint); try { int caret = 0; byte[] t = new byte[15]; foreach (var e in BitConverter.GetBytes((uint)Cmd.history)) t[caret++] = e; t[caret++] = (byte)vdp; t[caret++] = (byte)type; t[caret++] = 0x01; t[caret++] = Convert.ToByte(tStart.Year % 256); t[caret++] = Convert.ToByte(tStart.Year / 256); t[caret++] = (byte)tStart.Month; t[caret++] = (byte)tStart.Day; t[caret++] = Convert.ToByte(tEnd.Year % 256); t[caret++] = Convert.ToByte(tEnd.Year / 256); t[caret++] = (byte)tEnd.Month; t[caret++] = (byte)tEnd.Day; socket.Send(t); while (true) { byte mark = SocketReceiveByte(ref socket); switch (mark) { case 0x03: await Task.Delay(100); continue; case 0x01: return true; default: return false; } } } catch (Exception e) { Console.WriteLine(e.Message); return false; } } private async Task> DownloadAllPackage(byte[] cmd) { await Task.Delay(0); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 5000, SendTimeout = 5000 }; Queue result = new Queue(); try { int TotlalLength = 0; socket.Connect(IpPoint); socket.Send(cmd); byte mark = 0x00; do { mark = SocketReceiveByte(ref socket); switch (mark) { case 0x01: if (!SocketReceiveBytes(ref socket, ref result, BitConverter.ToInt32( SocketReceiveBytes(ref socket, 4), 0))) throw new Exception("Ошибка получения части пакета."); break; case 0x02: TotlalLength = BitConverter.ToInt32(SocketReceiveBytes(ref socket, 4), 0); break; } } while (mark != 0xFF); return result; } catch (Exception e) { Console.WriteLine(e.Message); return new Queue(); } finally { socket.Disconnect(false); } } private async Task DownloadAllPackage(string name) { if (TempDir.CheckFileExist(name)) return; var stream = TempDir.StartWrite(name); await Task.Delay(0); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 5000, SendTimeout = 5000 }; try { int TotlalLength = 0; socket.Connect(IpPoint); socket.Send(CreateCommand(Cmd.download_nh, name).ToArray()); byte mark = 0x00; do { mark = SocketReceiveByte(ref socket); switch (mark) { case 0x01: int size = BitConverter.ToInt32(SocketReceiveBytes(ref socket, 4), 0); stream.Write(SocketReceiveBytes(ref socket, size), 0, size); break; case 0x02: TotlalLength = BitConverter.ToInt32(SocketReceiveBytes(ref socket, 4), 0); break; } } while (mark != 0xFF); } catch (Exception e) { Console.WriteLine(e.Message); return; } finally { TempDir.EndWrite(name); stream.Close(); socket.Disconnect(false); } } private string ConvertBytesToString(ref Queue q) { StringBuilder result = new StringBuilder(); while (q.Count != 0) result.Append(ConvertByteToChar(q.Dequeue())); return result.ToString().Trim(); } private string ConvertBytesToString(byte[] b, int caret, int length) { StringBuilder result = new StringBuilder(); for (int i = caret; i < length + caret; i++) result.Append(ConvertByteToChar(b[i])); return result.ToString().Trim(); } private char ConvertByteToChar(byte b) { char temp; switch (b) { case 0x00: temp = ' '; break; case 0x80: temp = 'А'; break; case 0x81: temp = 'Б'; break; case 0x82: temp = 'В'; break; case 0x83: temp = 'Г'; break; case 0x84: temp = 'Д'; break; case 0x85: temp = 'Е'; break; case 0x86: temp = 'Ж'; break; case 0x87: temp = 'З'; break; case 0x88: temp = 'И'; break; case 0x89: temp = 'Й'; break; case 0x8a: temp = 'К'; break; case 0x8b: temp = 'Л'; break; case 0x8c: temp = 'М'; break; case 0x8d: temp = 'Н'; break; case 0x8e: temp = 'О'; break; case 0x8f: temp = 'П'; break; case 0x90: temp = 'Р'; break; case 0x91: temp = 'С'; break; case 0x92: temp = 'Т'; break; case 0x93: temp = 'У'; break; case 0x94: temp = 'Ф'; break; case 0x95: temp = 'Х'; break; case 0x96: temp = 'Ц'; break; case 0x97: temp = 'Ч'; break; case 0x98: temp = 'Ш'; break; case 0x99: temp = 'Щ'; break; case 0x9a: temp = 'Ъ'; break; case 0x9b: temp = 'Ы'; break; case 0x9c: temp = 'Ь'; break; case 0x9d: temp = 'Э'; break; case 0x9e: temp = 'Ю'; break; case 0x9f: temp = 'Я'; break; case 0xa0: temp = 'а'; break; case 0xa1: temp = 'б'; break; case 0xa2: temp = 'в'; break; case 0xa3: temp = 'г'; break; case 0xa4: temp = 'д'; break; case 0xa5: temp = 'е'; break; case 0xa6: temp = 'ж'; break; case 0xa7: temp = 'з'; break; case 0xa8: temp = 'и'; break; case 0xa9: temp = 'й'; break; case 0xaa: temp = 'к'; break; case 0xab: temp = 'л'; break; case 0xac: temp = 'м'; break; case 0xad: temp = 'н'; break; case 0xae: temp = 'о'; break; case 0xaf: temp = 'п'; break; case 0xe0: temp = 'р'; break; case 0xe1: temp = 'c'; break; case 0xe2: temp = 'т'; break; case 0xe3: temp = 'у'; break; case 0xe4: temp = 'ф'; break; case 0xe5: temp = 'х'; break; case 0xe6: temp = 'ц'; break; case 0xe7: temp = 'ч'; break; case 0xe8: temp = 'ш'; break; case 0xe9: temp = 'щ'; break; case 0xea: temp = 'ъ'; break; case 0xeb: temp = 'ы'; break; case 0xec: temp = 'ь'; break; case 0xed: temp = 'э'; break; case 0xee: temp = 'ю'; break; case 0xef: temp = 'я'; break; case 0xf0: temp = 'Ё'; break; case 0xf1: temp = 'ё'; break; default: temp = Convert.ToChar(b); break; } return temp; } private DateTime ConvertUnixTimeToDateTime(int unixTimeStamp) { DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).AddHours(5); return dtDateTime; } } class Old { private enum Cmd { pasp_download = 4, history = 20, download_nh = 21, dir_browse = 23 } private void CreateCommand(ref Queue q, Cmd cmd, string val, int dir = 0) { q.Clear(); foreach (var e in BitConverter.GetBytes((uint)cmd)) q.Enqueue(e); if (cmd == Cmd.dir_browse) q.Enqueue((byte)dir); foreach (var e in val) q.Enqueue((byte)e); q.Enqueue(0x00); } private bool SocketSendCommand(ref Socket socket, Cmd cmd, string val, int dir = 0) { try { int l = 5 + val.Length; if (cmd == Cmd.dir_browse) l++; byte[] s = new byte[l]; l = 0; foreach (var e in BitConverter.GetBytes((uint)cmd)) s[l++] = e; if (cmd == Cmd.dir_browse) s[l++] = (byte)dir; foreach (var e in val) s[l++] = (byte)e; socket.Send(s); return true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } private string ConvertBytesToString(ref Queue q, int l) { StringBuilder result = new StringBuilder(); //for (int i = 0; i < l; i++) // result.Append(ConvertByteToChar(q.Dequeue())); return result.ToString().Trim(); } } }