MainForm.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. using Hik.Api;
  2. using Hik.Api.Data;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. using RestSharp;
  6. using S7.Net;
  7. using System.Drawing.Imaging;
  8. using System.Threading.Channels;
  9. using System.Windows.Forms;
  10. namespace xicheji
  11. {
  12. public partial class MainForm : Form
  13. {
  14. private readonly Config config;
  15. private readonly List<WashRecord> washRecords = new();
  16. private static DateTime logDate = DateTime.Now;
  17. private static StreamWriter logWriter;
  18. private DateTime lastReceiveTime = DateTime.MinValue;
  19. private byte[]? currentDataBlock;
  20. private Plc? plc = null;
  21. private HikApi? hikApi = null;
  22. private string lastCarNo = string.Empty;
  23. public MainForm()
  24. {
  25. InitializeComponent();
  26. config = ConfigHelper.GetConfig();
  27. logWriter = new StreamWriter(DateTime.Now.ToString("yyyy_MM_dd") + ".log");
  28. }
  29. private void MainForm_Load(object sender, EventArgs e)
  30. {
  31. try
  32. {
  33. dataGridView1.AutoGenerateColumns = false;
  34. dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
  35. #region 测试代码: 表格数据
  36. washRecords.Add(new WashRecord()
  37. {
  38. DeviceId = "asdf",
  39. CarNum = "京123456",
  40. StartTime = new DateTime(2024, 6, 1, 12, 00, 00),
  41. EndTime = new DateTime(2024, 6, 1, 12, 30, 00),
  42. WashTime = 15,
  43. DryTime = 15,
  44. TotalElectricity = 10,
  45. TotalWater = 2,
  46. WaterPressure = 6,
  47. });
  48. #endregion
  49. dataGridView1.DataSource = washRecords;
  50. ConnectPLC();
  51. ConnectCamera();
  52. receivePLCTimer.Interval = config.PLCReceiveInterval * 1000;
  53. receivePLCTimer.Enabled = true;
  54. uploadTimer.Enabled = true;
  55. }
  56. catch (Exception ex)
  57. {
  58. MessageBox.Show(ex.Message + ex.StackTrace);
  59. }
  60. }
  61. private void btnSetting_Click(object sender, EventArgs e)
  62. {
  63. try
  64. {
  65. var settingForm = new SettingForm();
  66. if (settingForm.ShowDialog() == DialogResult.OK)
  67. {
  68. ConnectPLC();
  69. ConnectCamera();
  70. receivePLCTimer.Enabled = true;
  71. uploadTimer.Enabled = true;
  72. }
  73. }
  74. catch (Exception ex)
  75. {
  76. MessageBox.Show(ex.Message + ex.StackTrace);
  77. }
  78. }
  79. private void nowTimer_Tick(object sender, EventArgs e)
  80. {
  81. try
  82. {
  83. var now = DateTime.Now;
  84. lblTime.Text = $"{now.Month}月 {now.Day}日 {now.Hour}:{now:mm}:{now:ss}";
  85. }
  86. catch { }
  87. }
  88. public static void Log(object message)
  89. {
  90. if (message == null) return;
  91. if (DateTime.Now.Date != logDate.Date)
  92. {
  93. logDate = DateTime.Now;
  94. logWriter = new StreamWriter(DateTime.Now.ToString("yyyy_MM_dd") + ".log");
  95. }
  96. logWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss:fff> ") + " " + message);
  97. logWriter.Flush();
  98. }
  99. #region 读PLC数据
  100. private void ConnectPLC()
  101. {
  102. plc = new Plc(config.PLCType, config.PLCIP, int.Parse(config.PLCPort), 0, 1);
  103. plc.Open();
  104. if (!plc.IsConnected)
  105. {
  106. MessageBox.Show("PLC连接失败!");
  107. return;
  108. }
  109. }
  110. private void receivePLCTimer_Tick(object sender, EventArgs e)
  111. {
  112. try
  113. {
  114. if (plc == null || !plc.IsConnected)
  115. {
  116. receivePLCTimer.Enabled = false;
  117. return;
  118. }
  119. ReadPLCData();
  120. }
  121. catch (Exception ex)
  122. {
  123. receivePLCTimer.Enabled = false;
  124. MessageBox.Show(ex.Message + ex.StackTrace);
  125. }
  126. }
  127. private void ReadPLCData()
  128. {
  129. currentDataBlock = plc!.ReadBytes(DataType.DataBlock, 1, 0, 100);
  130. var time = new DateTime(
  131. DateTime.Now.Year,
  132. ReadPLCInt("当前月"),
  133. ReadPLCInt("当前日"),
  134. ReadPLCInt("当前时"),
  135. ReadPLCInt("当前分"),
  136. ReadPLCInt("当前秒"));
  137. var macAddress = ReadMacAddress();
  138. Log("macAddress: " + macAddress);
  139. if (string.IsNullOrEmpty(config.PLCMacAddress))
  140. {
  141. //第一次配置为空时,更新一下mac地址
  142. config.PLCMacAddress = macAddress;
  143. }
  144. //if (config.PLCMacAddress != macAddress)
  145. //{
  146. // //以后还不匹配就提示
  147. // MessageBox.Show("PLC设备Mac地址不匹配,请确认!");
  148. // return;
  149. //}
  150. if (time <= lastReceiveTime)
  151. {
  152. //已经读过这个时间的了
  153. return;
  154. }
  155. lastReceiveTime = time;
  156. ReadError();
  157. ReadStatus();
  158. lblWashCount.Text = ReadPLCString("洗车次数");
  159. lblTotalWater.Text = ReadPLCString("累计用水量");
  160. lblTotalElectricity.Text = ReadPLCString("累计用电量");
  161. //.Text = ReadPLCStringValue("当前流量");
  162. lblCurrentElectricity.Text = ReadPLCString("当前功率");
  163. lblCurrentWaterP.Text = ReadPLCString("当前压力");
  164. var myCrc = CRCCheck(currentDataBlock);
  165. var readCrc = ReadPLCInt("CRC");
  166. if (myCrc != readCrc)
  167. {
  168. //receivePLCTimer.Enabled = false;
  169. //MessageBox.Show("CRC不匹配!");
  170. //return;
  171. }
  172. if (ReadPLCInt("最后一次洗车开始月") != 0)
  173. {
  174. if (string.IsNullOrEmpty(lastCarNo))
  175. {
  176. receivePLCTimer.Enabled = false;
  177. MessageBox.Show("未检测到车牌信息,请检查是否识别正常");
  178. return;
  179. }
  180. //洗车完成后才有数据的
  181. var washStartTime = new DateTime(
  182. DateTime.Now.Year,
  183. ReadPLCInt("最后一次洗车开始月"),
  184. ReadPLCInt("最后一次洗车开始日"),
  185. ReadPLCInt("最后一次洗车开始时"),
  186. ReadPLCInt("最后一次洗车开始分"),
  187. ReadPLCInt("最后一次洗车开始秒"));
  188. var washEndTime = new DateTime(
  189. DateTime.Now.Year,
  190. ReadPLCInt("最后一次洗车结束月"),
  191. ReadPLCInt("最后一次洗车结束日"),
  192. ReadPLCInt("最后一次洗车结束时"),
  193. ReadPLCInt("最后一次洗车结束分"),
  194. ReadPLCInt("最后一次洗车结束秒"));
  195. var washRecord = new WashRecord()
  196. {
  197. DeviceId = macAddress,
  198. CarNum = lastCarNo,
  199. StartTime = washStartTime,
  200. EndTime = washEndTime,
  201. DryTime = ReadPLCInt("最后一次洗车风干时长"),
  202. TotalElectricity = ReadPLCInt("最后一次洗车用电"),
  203. TotalWater = ReadPLCInt("最后一次洗车用水"),
  204. WashTime = ReadPLCInt("最后一次洗车总时长"),
  205. WaterPressure = ReadPLCInt("最后一次洗车水压"),
  206. };
  207. washRecords.Add(washRecord);
  208. //洗车完成后重置车牌信息
  209. lastCarNo = string.Empty;
  210. }
  211. }
  212. private static readonly ushort[] crcTable = new ushort[256] {
  213. 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
  214. 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
  215. 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
  216. 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
  217. 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
  218. 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
  219. 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
  220. 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
  221. 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
  222. 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
  223. 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
  224. 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
  225. 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
  226. 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
  227. 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
  228. 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
  229. 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
  230. 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
  231. 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
  232. 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
  233. 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
  234. 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
  235. 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
  236. 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
  237. 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
  238. 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
  239. 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
  240. 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
  241. 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
  242. 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
  243. 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
  244. 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
  245. };
  246. private static ushort CRCCheck(byte[] data)
  247. {
  248. ushort crc = 0xFFFF;
  249. foreach (byte b in data)
  250. {
  251. byte tableIndex = (byte)(((crc >> 8) ^ b) & 0xFF);
  252. crc = (ushort)((crc << 8) ^ crcTable[tableIndex]);
  253. }
  254. return crc;
  255. }
  256. private string ReadMacAddress()
  257. {
  258. var mac1 = ReadPLCString("MAC1");
  259. var mac2 = ReadPLCString("MAC2");
  260. var mac3 = ReadPLCString("MAC3");
  261. var mac4 = ReadPLCString("MAC4");
  262. var mac5 = ReadPLCString("MAC5");
  263. var mac6 = ReadPLCString("MAC6");
  264. return $"{mac1:X4}:{mac2:X4}:{mac3:X4}:{mac4:X4}:{mac5:X4}:{mac6:X4}";
  265. }
  266. private void ReadStatus()
  267. {
  268. lblStatus.Text = string.Empty;
  269. var statuses = new List<string>() {
  270. "洗车中", "清洗中", "沥水中",
  271. "出车中", "风干中"};
  272. foreach (var status in statuses)
  273. {
  274. if (ReadPLCBool(status))
  275. {
  276. lblStatus.Text = status;
  277. break;
  278. }
  279. }
  280. }
  281. private void ReadError()
  282. {
  283. lblError.Text = string.Empty;
  284. var errors = new List<string>() {
  285. "急停", "冲洗泵故障", "反洗泵故障",
  286. "清淤泵故障", "伴热故障", "风刀故障" };
  287. foreach (var error in errors)
  288. {
  289. if (ReadPLCBool(error))
  290. {
  291. lblError.Text = error;
  292. break;
  293. }
  294. }
  295. }
  296. private string ReadPLCString(string name)
  297. {
  298. var variable = ConfigHelper.FindVariable(name);
  299. if (variable == null || currentDataBlock == null)
  300. return string.Empty;
  301. ParsePLCKey(variable.Key, out _, out _, out var varType, out var address, out var bitNumber);
  302. if (varType == VarType.DWord)
  303. {
  304. var value = S7.Net.Types.DWord.FromByteArray(currentDataBlock.Take(new Range(address, address + 4)).ToArray());
  305. return $"{value} {variable.Desc}".TrimEnd();
  306. }
  307. else if (varType == VarType.Word)
  308. {
  309. var value = S7.Net.Types.Word.FromByteArray(currentDataBlock.Take(new Range(address, address + 2)).ToArray());
  310. return $"{value} {variable.Desc}".TrimEnd();
  311. }
  312. else if (varType == VarType.Byte)
  313. {
  314. var value = S7.Net.Types.Byte.FromByteArray(currentDataBlock.Take(new Range(address, address + 1)).ToArray());
  315. return $"{value} {variable.Desc}".TrimEnd();
  316. }
  317. return string.Empty;
  318. }
  319. private int ReadPLCInt(string name)
  320. {
  321. var variable = ConfigHelper.FindVariable(name);
  322. if (variable == null || currentDataBlock == null)
  323. return 0;
  324. ParsePLCKey(variable.Key, out var dataType, out var dbNumber, out var varType, out var address, out var bitNumber);
  325. if (varType == VarType.DWord)
  326. {
  327. var value = S7.Net.Types.DWord.FromByteArray(currentDataBlock.Take(new Range(address, address + 4)).ToArray());
  328. return (int)value;
  329. }
  330. else if (varType == VarType.Word)
  331. {
  332. var value = S7.Net.Types.Word.FromByteArray(currentDataBlock.Take(new Range(address, address + 2)).ToArray());
  333. return value;
  334. }
  335. return 0;
  336. }
  337. private bool ReadPLCBool(string name)
  338. {
  339. var variable = ConfigHelper.FindVariable(name);
  340. if (variable == null || currentDataBlock == null)
  341. return false;
  342. ParsePLCKey(variable.Key, out _, out _, out _, out var address, out var bitNumber);
  343. var value = S7.Net.Types.Boolean.GetValue(currentDataBlock[address], bitNumber);
  344. return value;
  345. }
  346. private static void ParsePLCKey(string plcKey, out DataType dataType, out int dbNumber, out VarType varType, out int address, out int bitNumber)
  347. {
  348. bitNumber = -1;
  349. dbNumber = 0;
  350. switch (plcKey.Substring(0, 2))
  351. {
  352. case "DB":
  353. string[] strings = plcKey.Split(new char[] { '.' });
  354. if (strings.Length < 2)
  355. throw new InvalidAddressException("To few periods for DB address");
  356. dataType = DataType.DataBlock;
  357. dbNumber = int.Parse(strings[0].Substring(2));
  358. address = int.Parse(strings[1].Substring(3));
  359. string dbType = strings[1].Substring(0, 3);
  360. switch (dbType)
  361. {
  362. case "DBB":
  363. varType = VarType.Byte;
  364. return;
  365. case "DBW":
  366. varType = VarType.Word;
  367. return;
  368. case "DBD":
  369. varType = VarType.DWord;
  370. return;
  371. case "DBX":
  372. bitNumber = int.Parse(strings[2]);
  373. if (bitNumber > 7)
  374. throw new InvalidAddressException("Bit can only be 0-7");
  375. varType = VarType.Bit;
  376. return;
  377. default:
  378. throw new InvalidAddressException();
  379. }
  380. case "IB":
  381. case "EB":
  382. // Input byte
  383. dataType = DataType.Input;
  384. dbNumber = 0;
  385. address = int.Parse(plcKey.Substring(2));
  386. varType = VarType.Byte;
  387. return;
  388. case "IW":
  389. case "EW":
  390. // Input word
  391. dataType = DataType.Input;
  392. dbNumber = 0;
  393. address = int.Parse(plcKey.Substring(2));
  394. varType = VarType.Word;
  395. return;
  396. case "ID":
  397. case "ED":
  398. // Input double-word
  399. dataType = DataType.Input;
  400. dbNumber = 0;
  401. address = int.Parse(plcKey.Substring(2));
  402. varType = VarType.DWord;
  403. return;
  404. case "QB":
  405. case "AB":
  406. case "OB":
  407. // Output byte
  408. dataType = DataType.Output;
  409. dbNumber = 0;
  410. address = int.Parse(plcKey.Substring(2));
  411. varType = VarType.Byte;
  412. return;
  413. case "QW":
  414. case "AW":
  415. case "OW":
  416. // Output word
  417. dataType = DataType.Output;
  418. dbNumber = 0;
  419. address = int.Parse(plcKey.Substring(2));
  420. varType = VarType.Word;
  421. return;
  422. case "QD":
  423. case "AD":
  424. case "OD":
  425. // Output double-word
  426. dataType = DataType.Output;
  427. dbNumber = 0;
  428. address = int.Parse(plcKey.Substring(2));
  429. varType = VarType.DWord;
  430. return;
  431. case "MB":
  432. // Memory byte
  433. dataType = DataType.Memory;
  434. dbNumber = 0;
  435. address = int.Parse(plcKey.Substring(2));
  436. varType = VarType.Byte;
  437. return;
  438. case "MW":
  439. // Memory word
  440. dataType = DataType.Memory;
  441. dbNumber = 0;
  442. address = int.Parse(plcKey.Substring(2));
  443. varType = VarType.Word;
  444. return;
  445. case "MD":
  446. // Memory double-word
  447. dataType = DataType.Memory;
  448. dbNumber = 0;
  449. address = int.Parse(plcKey.Substring(2));
  450. varType = VarType.DWord;
  451. return;
  452. default:
  453. switch (plcKey.Substring(0, 1))
  454. {
  455. case "E":
  456. case "I":
  457. // Input
  458. dataType = DataType.Input;
  459. varType = VarType.Bit;
  460. break;
  461. case "Q":
  462. case "A":
  463. case "O":
  464. // Output
  465. dataType = DataType.Output;
  466. varType = VarType.Bit;
  467. break;
  468. case "M":
  469. // Memory
  470. dataType = DataType.Memory;
  471. varType = VarType.Bit;
  472. break;
  473. case "T":
  474. // Timer
  475. dataType = DataType.Timer;
  476. dbNumber = 0;
  477. address = int.Parse(plcKey.Substring(1));
  478. varType = VarType.Timer;
  479. return;
  480. case "Z":
  481. case "C":
  482. // Counter
  483. dataType = DataType.Counter;
  484. dbNumber = 0;
  485. address = int.Parse(plcKey.Substring(1));
  486. varType = VarType.Counter;
  487. return;
  488. default:
  489. throw new InvalidAddressException(string.Format("{0} is not a valid address", plcKey.Substring(0, 1)));
  490. }
  491. string txt2 = plcKey.Substring(1);
  492. if (txt2.IndexOf(".") == -1)
  493. throw new InvalidAddressException("To few periods for DB address");
  494. address = int.Parse(txt2.Substring(0, txt2.IndexOf(".")));
  495. bitNumber = int.Parse(txt2.Substring(txt2.IndexOf(".") + 1));
  496. if (bitNumber > 7)
  497. throw new InvalidAddressException("Bit can only be 0-7");
  498. return;
  499. }
  500. }
  501. #endregion
  502. #region 上传到洗车平台
  503. private async void uploadTimer_Tick(object sender, EventArgs e)
  504. {
  505. try
  506. {
  507. await UploadPlatform();
  508. }
  509. catch (Exception ex)
  510. {
  511. uploadTimer.Enabled = false;
  512. MessageBox.Show(ex.Message + ex.StackTrace);
  513. }
  514. }
  515. private async Task UploadPlatform()
  516. {
  517. var restClient = new RestClient(config.Server);
  518. var request = new RestRequest("cyft/common/carWashRecord", Method.Post);
  519. // 测试代码
  520. WashRecord washRecord = new WashRecord();
  521. var jsonBody = new
  522. {
  523. deviceId = washRecord.DeviceId, //洗车机器mac地址
  524. carNo = washRecord.CarNum, //车牌号码
  525. beginTime = washRecord.StartTime.ToString("yyyy-MM-dd HH:mm:ss"), //洗车开始时间
  526. endTime = washRecord.EndTime.ToString("yyyy-MM-dd HH:mm:ss"), //洗车结束时间
  527. washTime = washRecord.WashTime, //洗车时长(s)
  528. widnowsDefender = washRecord.TotalWater, //用水量(t)
  529. waterPressure = washRecord.WaterPressure, //压力(MPa)
  530. picBase64 = ImageToBase64(pbCamera.Image, ImageFormat.Jpeg), //洗车图片base64
  531. };
  532. request.AddParameter("application/json", JsonConvert.SerializeObject(jsonBody), ParameterType.RequestBody);
  533. var response = await restClient.ExecuteAsync(request);
  534. if (response == null) return;
  535. }
  536. #endregion
  537. #region 摄像头
  538. private void btnConnectCamera_Click(object sender, EventArgs e)
  539. {
  540. try
  541. {
  542. ConnectCamera();
  543. }
  544. catch (Exception ex)
  545. {
  546. MessageBox.Show(ex.Message + ex.StackTrace);
  547. }
  548. }
  549. private void ConnectCamera()
  550. {
  551. try
  552. {
  553. cboCameraChannel.DisplayMember = "Display";
  554. cboCameraChannel.ValueMember = "Value";
  555. cboCameraChannel.Items.Clear();
  556. hikApi = HikApi.Login(config.CameraIP, int.Parse(config.CameraPort),
  557. config.CameraUserName, config.CameraPassword) as HikApi;
  558. if (hikApi == null || !hikApi.Connected)
  559. {
  560. MessageBox.Show("摄像头连接失败!");
  561. return;
  562. }
  563. var channels = hikApi.IpChannels.ToList();
  564. #region 测试代码: 测试摄像头信道
  565. //channels = new List<IpChannel>();
  566. //channels.Add(new IpChannel(33, true, "channl1"));
  567. //channels.Add(new IpChannel(34, false, "channl2"));
  568. //channels.Add(new IpChannel(35, true, "channl3"));
  569. //channels.Add(new IpChannel(36, false, "channl4"));
  570. //channels.Add(new IpChannel(37, false, "channl5"));
  571. #endregion
  572. foreach (var c in channels)
  573. {
  574. cboCameraChannel.Items.Add(new
  575. {
  576. Display = $"{c.Name}({c.ChannelNumber}) {(c.IsOnline ? "在线" : "离线")})",
  577. Value = c.ChannelNumber,
  578. Channel = c,
  579. });
  580. }
  581. if (cboCameraChannel.Items.Count > 0 && cboCameraChannel.SelectedIndex == -1)
  582. {
  583. cboCameraChannel.SelectedIndex = 0;
  584. }
  585. }
  586. catch (Exception ex)
  587. {
  588. MessageBox.Show(ex.Message + ex.StackTrace);
  589. }
  590. }
  591. private void cboCameraChannel_SelectedIndexChanged(object sender, EventArgs e)
  592. {
  593. try
  594. {
  595. var channelNumber = ((dynamic)(cboCameraChannel.SelectedItem)).Value;
  596. hikApi?.PlaybackService.StartPlayBack(channelNumber, pbCamera.Handle);
  597. }
  598. catch (Exception ex)
  599. {
  600. MessageBox.Show(ex.Message + ex.StackTrace);
  601. }
  602. }
  603. #endregion
  604. #region 服务接口回调->更新汽车信息
  605. public void UpdateTest(DateTime now)
  606. {
  607. this.Invoke(() =>
  608. {
  609. this.Text = now.ToString();
  610. });
  611. }
  612. public void UpdateCar(Plateresult result)
  613. {
  614. this.Invoke(() =>
  615. {
  616. var carNo = result.license;
  617. var base64String = result.imageFile;
  618. var colorType = result.colorType;
  619. //var image = Base64ToImage(base64String);
  620. this.lastCarNo = carNo;
  621. });
  622. }
  623. #endregion
  624. #region Image <-> Base64
  625. public static Image Base64ToImage(string base64String)
  626. {
  627. byte[] imageBytes = Convert.FromBase64String(base64String);
  628. using var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
  629. ms.Write(imageBytes, 0, imageBytes.Length);
  630. Image image = Image.FromStream(ms, true);
  631. return image;
  632. }
  633. public static string ImageToBase64(Image image, ImageFormat format)
  634. {
  635. if (image == null) return string.Empty;
  636. using var memoryStream = new MemoryStream();
  637. image.Save(memoryStream, format);
  638. var imageBytes = memoryStream.ToArray();
  639. return Convert.ToBase64String(imageBytes);
  640. }
  641. #endregion
  642. }
  643. }