MainForm.cs 28 KB

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