FrmStandAloneMetering.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. using com.hnshituo.core.webapp.vo;
  2. using Common;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.IO;
  8. using System.IO.Ports;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Windows.Forms;
  12. namespace FrmStandAloneMetering
  13. {
  14. /// <summary>
  15. /// 仪表状态
  16. /// </summary>
  17. public enum MeterStatus
  18. {
  19. /// <summary>
  20. /// Stable 稳定
  21. /// </summary>
  22. Stable,
  23. /// <summary>
  24. /// 不稳定
  25. /// </summary>
  26. UnStable,
  27. /// <summary>
  28. /// 空磅
  29. /// </summary>
  30. Null,
  31. ///// <summary>
  32. ///// 未连接
  33. ///// </summary>
  34. UnConnect,
  35. ///// <summary>
  36. ///// 已连接
  37. ///// </summary>
  38. Connect
  39. }
  40. public partial class FrmStandAloneMetering : Form
  41. {
  42. private string strComPara; //仪表参数
  43. private int messageLength; //报文长度
  44. private string strSeparate;//分割符
  45. private int startPosition; //开始取值位置
  46. private int dataLength; //数据长度
  47. private int sleepTime; //采样频率
  48. private int stableTime; //稳定时间
  49. private int stableCount; //稳定次数
  50. private int stableDiff; //稳定次数
  51. private double tmpWeight; //临时重量,用于判断是否稳定状态
  52. private int weightStabCount; //波动次数
  53. private SerialPort serialPort1; //数据采集串口
  54. private bool blThreadFlag;//数据采集线程开关
  55. private StringBuilder weightLog = new StringBuilder(); //重量日志的文件
  56. private MeterWorkCarActualFirstService actualFirstService = new MeterWorkCarActualFirstService();
  57. public FrmStandAloneMetering()
  58. {
  59. InitializeComponent();
  60. }
  61. private void FrmStandAloneMetering_Load(object sender, EventArgs e)
  62. {
  63. strComPara = ConfigurationManager.AppSettings["ComPara"].ToString().Trim(); //仪表参数COM口
  64. messageLength = Convert.ToInt32(ConfigurationManager.AppSettings["MessageLength"].ToString().Trim()); //报文长度
  65. strSeparate = ConfigurationManager.AppSettings["Separate"].ToString().Trim();//分割符
  66. startPosition = Convert.ToInt32(ConfigurationManager.AppSettings["StartPosition"].ToString().Trim());//开始取值位置
  67. dataLength = Convert.ToInt32(ConfigurationManager.AppSettings["DataLength"].ToString().Trim());// 数据长度
  68. sleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"].ToString().Trim());//采样频率
  69. stableTime = Convert.ToInt32(ConfigurationManager.AppSettings["StableTime"].ToString().Trim());//稳定时间
  70. stableDiff = Convert.ToInt32(ConfigurationManager.AppSettings["StableDiff"].ToString().Trim());//稳定重量
  71. stableCount = stableTime * 1000 / sleepTime;//稳定次数
  72. //界面COM赋值
  73. if (!String.IsNullOrEmpty(strComPara) && strComPara.Contains(","))
  74. {
  75. string[] strParams = strComPara.Split(new char[] { ',' });
  76. cbChooseCom.Text = strParams[0];
  77. }
  78. //物料下拉框赋值
  79. DataTable dtMatterInfo = selectMatterInfo();
  80. this.cbMatterName.DataSource = dtMatterInfo;
  81. this.cbMatterName.DisplayMember = "name";
  82. this.cbMatterName.ValueMember = "value";
  83. //发货单位下拉框赋值
  84. DataTable dtForwardingUnit = selectCustomerInfo();
  85. this.cbForwardingUnitName.DataSource = dtForwardingUnit;
  86. this.cbForwardingUnitName.DisplayMember = "name";
  87. this.cbForwardingUnitName.ValueMember = "value";
  88. //收货单位下拉框赋值
  89. DataTable dtReceivingUint = selectCustomerInfo();
  90. this.cbReceivingUintName.DataSource = dtReceivingUint;
  91. this.cbReceivingUintName.DisplayMember = "name";
  92. this.cbReceivingUintName.ValueMember = "value";
  93. //计量点下拉框赋值
  94. DataTable dtSpotInfo = selectSpotInfo();
  95. this.cbBaseSpot.DataSource = dtSpotInfo;
  96. this.cbBaseSpot.DisplayMember = "name";
  97. this.cbBaseSpot.ValueMember = "value";
  98. //界面稳定时间赋值
  99. cbStableSchedule.Text = stableTime.ToString();
  100. tmpWeight = 0;//临时重量
  101. weightStabCount = 0; //波动次数
  102. }
  103. #region 用户控件的事件
  104. /// <summary>
  105. /// 开启数据采集
  106. /// </summary>
  107. /// <param name="sender"></param>
  108. /// <param name="e"></param>
  109. private void btnCollection_Click(object sender, EventArgs e)
  110. {
  111. if (blThreadFlag)
  112. {
  113. MessageBox.Show("采集程序已经运行,禁止重新进行采集!");
  114. return;
  115. }
  116. blThreadFlag = true;
  117. System.Threading.Thread DataCollectThread = new System.Threading.Thread(new System.Threading.ThreadStart(DataCollect));
  118. DataCollectThread.Start();
  119. }
  120. /// <summary>
  121. /// 上传本地的计量数据
  122. /// </summary>
  123. /// <param name="sender"></param>
  124. /// <param name="e"></param>
  125. private void btnUploadData_Click(object sender, EventArgs e)
  126. {
  127. uploadData();
  128. }
  129. /// <summary>
  130. /// 下载服务器的基础数据
  131. /// </summary>
  132. /// <param name="sender"></param>
  133. /// <param name="e"></param>
  134. private void btnDownloadData_Click(object sender, EventArgs e)
  135. {
  136. // 删除CSV文件
  137. Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv");
  138. // 获取物料信息
  139. MeterBaseMatterInfoService meterBaseMatterInfo = new MeterBaseMatterInfoService();//物料服务
  140. MeterBaseMatterInfo MatterInfo1 = new MeterBaseMatterInfo();
  141. MatterInfo1.validFlag = "1";
  142. MatterInfo1.pageNum = 1;
  143. MatterInfo1.pageSize = 9999;
  144. RESTfulResult<List<MeterBaseMatterInfo>> rmx = meterBaseMatterInfo.doQueryListLike(MatterInfo1);
  145. // 重新保存CSV文件
  146. saveMatterInfo(rmx);
  147. // 删除CSV文件
  148. Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv");
  149. // 获取客商信息
  150. MeterBaseCustomerSupplierService service2 = new MeterBaseCustomerSupplierService();//物料服务
  151. MeterBaseCustomerSupplier customerInfo1 = new MeterBaseCustomerSupplier();
  152. customerInfo1.validFlag = "1";
  153. RESTfulResult<List<MeterBaseCustomerSupplier>> rmx2 = service2.doQuery(customerInfo1);
  154. // 重新保存CSV文件
  155. saveCustomerInfo(rmx2);
  156. // 删除CSV文件
  157. Utils.FileUtil.DeleteFile(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv");
  158. // 获取客商信息
  159. MeterBaseSpotInfoService service3 = new MeterBaseSpotInfoService();//物料服务
  160. MeterBaseSpotInfo customerInfo2 = new MeterBaseSpotInfo();
  161. customerInfo2.validFlag = "1";
  162. RESTfulResult<List<MeterBaseSpotInfo>> rmx3 = service3.doQueryWf(customerInfo2);
  163. // 重新保存CSV文件
  164. saveSpotInfo(rmx3);
  165. }
  166. /// <summary>
  167. /// 数据查询
  168. /// </summary>
  169. /// <param name="sender"></param>
  170. /// <param name="e"></param>
  171. private void btQuery_Click(object sender, EventArgs e)
  172. {
  173. doQuery();
  174. }
  175. /// <summary>
  176. /// 毛重保存
  177. /// </summary>
  178. /// <param name="sender"></param>
  179. /// <param name="e"></param>
  180. private void btSaveGross_Click(object sender, EventArgs e)
  181. {
  182. saveData("0"); //毛重保存(0=毛重;1=常规皮重)
  183. doQuery();
  184. }
  185. /// <summary>
  186. /// 皮重保存
  187. /// </summary>
  188. /// <param name="sender"></param>
  189. /// <param name="e"></param>
  190. private void btSaveTare_Click(object sender, EventArgs e)
  191. {
  192. saveData("1"); //毛重保存(0=毛重;1=常规皮重)
  193. doQuery();
  194. }
  195. /// <summary>
  196. /// 界面关闭
  197. /// </summary>
  198. /// <param name="sender"></param>
  199. /// <param name="e"></param>
  200. private void FrmStandAloneMetering_FormClosing(object sender, FormClosingEventArgs e)
  201. {
  202. blThreadFlag = false;
  203. System.Threading.Thread.Sleep(sleepTime * 2);
  204. if (serialPort1 != null)
  205. {
  206. serialPort1.Close();
  207. }
  208. Application.Exit();
  209. }
  210. /// <summary>
  211. /// 稳定时间选择事件
  212. /// </summary>
  213. /// <param name="sender"></param>
  214. /// <param name="e"></param>
  215. private void cbStableSchedule_TextChanged(object sender, EventArgs e)
  216. {
  217. stableTime = Convert.ToInt32(cbStableSchedule.Text.Trim());//稳定时间
  218. stableCount = stableTime * 1000 / sleepTime;//稳定次数
  219. }
  220. /// <summary>
  221. /// COM口下拉事件
  222. /// </summary>
  223. /// <param name="sender"></param>
  224. /// <param name="e"></param>
  225. private void cbChooseCom_TextChanged(object sender, EventArgs e)
  226. {
  227. if (blThreadFlag)
  228. {
  229. MessageBox.Show("采集程序已经运行,禁止重新调整COM口!");
  230. return;
  231. }
  232. }
  233. #endregion 用户控件的事件
  234. #region 数据采集
  235. /// <summary>
  236. /// 数据采集线程
  237. /// </summary>
  238. private void DataCollect()
  239. {
  240. if (!blThreadFlag) return;
  241. string[] strParams = strComPara.Split(new char[] { ',' });
  242. Parity parity = Parity.None;
  243. if (strParams[2].ToUpper() == "ODD")
  244. {
  245. parity = Parity.Odd;
  246. }
  247. if (strParams[2].ToUpper() == "EVEN")
  248. {
  249. parity = Parity.Even;
  250. }
  251. StopBits stopBits = StopBits.None;
  252. if (strParams[4] == "1")
  253. {
  254. stopBits = StopBits.One;
  255. }
  256. if (strParams[4] == "1.5")
  257. {
  258. stopBits = StopBits.OnePointFive;
  259. }
  260. if (strParams[4] == "2")
  261. {
  262. stopBits = StopBits.Two;
  263. }
  264. serialPort1 = new SerialPort(strParams[0], Int32.Parse(strParams[1]),
  265. parity, Int32.Parse(strParams[3]), stopBits);
  266. while (!serialPort1.IsOpen)
  267. {
  268. try
  269. {
  270. serialPort1.Open();
  271. }
  272. catch (Exception err)
  273. {
  274. WriteCatchLog(err.ToString());
  275. }
  276. System.Threading.Thread.Sleep(500);
  277. }
  278. StringBuilder stringBuilder = new StringBuilder();
  279. string strtmp = "";
  280. while (blThreadFlag)
  281. {
  282. try
  283. {
  284. System.Threading.Thread.Sleep(sleepTime);
  285. if (serialPort1.BytesToRead > 0)
  286. {
  287. strtmp = serialPort1.ReadExisting();
  288. stringBuilder.Append(strtmp);
  289. //"US,GS,+0073.34 t\r\nUS,GS,+0073.96 t\r\nUS,GS,+0071.36 t\r\nUS,GS,+0070.40 t\r\nUS,GS,+0073.06 t\r\nUS,GS,+0073.16 t\r\nUS,GS,+0071.72 t\r\nUS,GS,+0073.30 t\r\nUS,GS,+0074.16 t\r\n"
  290. //0252.50 kg
  291. //20 20 0D 0A 7F 30 32 35 32 2E 35 30 20 6B 67
  292. //03 04 0D 0A FF 30 30 30 30 31 35 20 6B 67
  293. //char strSeparate = (char)0x6B;
  294. if (stringBuilder.ToString().LastIndexOf(strSeparate) >= 0)
  295. {
  296. if (stringBuilder.ToString().LastIndexOf(strSeparate) < messageLength)//不完整报文,抛掉
  297. {
  298. stringBuilder.Remove(0, stringBuilder.ToString().LastIndexOf(strSeparate) + strSeparate.Length);
  299. //stringBuilder.Remove(0, stringBuilder.ToString().LastIndexOf(strSeparate) + strSeparate.Length);
  300. }
  301. int index = stringBuilder.ToString().LastIndexOf(strSeparate);
  302. if ((index - messageLength) < 0)
  303. continue;
  304. string strData = stringBuilder.ToString().Substring(index - messageLength, messageLength + strSeparate.Length);
  305. // WriteCatchLog("strData " + strData);
  306. string weight = strData.Substring(startPosition, dataLength);
  307. if ("T".Equals(strSeparate.ToUpper()))
  308. {
  309. //单位为T是做特殊处理,界面显示的是T
  310. weight = (Convert.ToDouble(weight) * 1000) + "";
  311. }
  312. //WriteCatchLog("weight " + weight);
  313. stringBuilder.Remove(0, stringBuilder.Length);
  314. ucStorageWeightT1.setWgt(Math.Round(Convert.ToDouble(weight), 3));
  315. DoShowWeightStatus(Convert.ToDouble(weight));
  316. }
  317. }
  318. }
  319. catch (Exception err)
  320. {
  321. MessageBox.Show("串口打开异常!异常原因" + err.ToString());
  322. WriteCatchLog("DataCollect1" + err.ToString());
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// 重量稳定判断
  328. /// </summary>
  329. /// <param name="_weight"></param>
  330. public void DoShowWeightStatus(double _weight)
  331. {
  332. if (Math.Abs(_weight) < 50)
  333. {
  334. //不稳定状态;红灯
  335. ucStorageWeightT1.setStable(false);
  336. return;
  337. }
  338. //波动在范围内时,稳定次数+1,临时重量不变;波动范围超出时,稳定次数清零,更新临时重量,
  339. int inDiff = Math.Abs(Convert.ToInt32(tmpWeight - _weight));
  340. if (inDiff < stableDiff)
  341. {
  342. weightStabCount += 1;
  343. }
  344. else
  345. {
  346. weightStabCount = 0;
  347. }
  348. //WriteCatchLog("_tmpWeight: " + _tmpWeight + " _weight: " + _weight + " inDiff: "+inDiff+ " StabCount : " + weightStabCount);
  349. tmpWeight = Convert.ToSingle(_weight);
  350. //重量30kg内波动超过10次认为重量稳定
  351. if (weightStabCount > stableCount)
  352. {
  353. //稳定状态;绿灯
  354. ucStorageWeightT1.setStable(true);
  355. weightStabCount = stableCount;
  356. }
  357. else
  358. {
  359. ucStorageWeightT1.setStable(false);
  360. }
  361. }
  362. #endregion 数据采集
  363. /// <summary>
  364. /// 重量保存:0=毛重;1=常规皮重
  365. /// </summary>
  366. /// <param name="strWeightType"></param>
  367. private void saveData(string strWeightType)
  368. {
  369. MeterWorkCarActualFirst actualFirst = new MeterWorkCarActualFirst(); //一次计量实体
  370. actualFirst.actualFirstNo = "CAR" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); //主键
  371. actualFirst.carNo = tbCarNo.Text.Trim();//车号
  372. actualFirst.baseSpotNo = cbBaseSpot.SelectedValue.ToString().Trim();//计量点
  373. //actualFirst.meterTypeName = cbMeterTypeName.Text.Trim();//业务类型
  374. //actualFirst.contractNo = cbContractNo.Text.Trim();//合同号
  375. //actualFirst.batchNo = tbBatchNo.Text.Trim();//批次号
  376. //actualFirst.heatNo = tbHeatNo.Text.Trim();//炉号
  377. //actualFirst.shipmentNum = Convert.ToInt32(string.IsNullOrEmpty(tbShipmentNum.Text.Trim()) ? "0" : tbShipmentNum.Text.Trim());//包数/数量
  378. actualFirst.matterNo = cbMatterName.SelectedValue.ToString().Trim();//物资名称
  379. actualFirst.receivingUintNo = cbReceivingUintName.SelectedValue.ToString().Trim();//收货单位
  380. actualFirst.forwardingUnitNo = cbForwardingUnitName.SelectedValue.ToString().Trim();//发货单位
  381. //actualFirst.customerSupplierName = cbCustomerSupplierName.Text.Trim();//供应商
  382. //actualFirst.loadPointName = cbLoadPointName.Text.Trim();//卸货地点
  383. actualFirst.memo = tbMemo.Text.Trim();//备注
  384. actualFirst.weightType = strWeightType;//重量类型
  385. actualFirst.meterWeight = ucStorageWeightT1.getWgt() * 1000;
  386. //DataTable csvDataTable = OpenCSV(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv");
  387. if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd")) == false
  388. || System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv") == false)
  389. {
  390. StringBuilder actualFirstLogHead = new StringBuilder(); //一次计量数据保存文件
  391. actualFirstLogHead.Append("createTime,");//若第一行默认为当前时间则第一行多个逗号
  392. actualFirstLogHead.Append("actualFirstNo,");
  393. actualFirstLogHead.Append("carNo,");
  394. actualFirstLogHead.Append("baseSpotNo,");
  395. //actualFirstLogHead.Append("meterTypeName,");
  396. //actualFirstLogHead.Append("contractNo,");
  397. //actualFirstLogHead.Append("batchNo,");
  398. //actualFirstLogHead.Append("heatNo,");
  399. //actualFirstLogHead.Append("shipmentNum,");
  400. actualFirstLogHead.Append("matterNo,");
  401. actualFirstLogHead.Append("receivingUintNo,");
  402. actualFirstLogHead.Append("forwardingUnitNo,");
  403. //actualFirstLogHead.Append("customerSupplierName,");
  404. //actualFirstLogHead.Append("loadPointName,");
  405. actualFirstLogHead.Append("memo,");
  406. actualFirstLogHead.Append("weightType,"); //最后一行不要逗号
  407. actualFirstLogHead.Append("meterWeight");
  408. logCsv.WriteDataLog("actualFirst", actualFirstLogHead.ToString());
  409. }
  410. StringBuilder actualFirstLog = new StringBuilder(); //一次计量数据保存文件
  411. actualFirstLog.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",");
  412. actualFirstLog.Append(actualFirst.actualFirstNo.ToString() + ",");
  413. actualFirstLog.Append(actualFirst.carNo.ToString() + ",");
  414. actualFirstLog.Append(actualFirst.baseSpotNo.ToString() + ",");
  415. // actualFirstLog.Append(actualFirst.meterTypeName.ToString() + ",");
  416. //actualFirstLog.Append(actualFirst.contractNo.ToString() + ",");
  417. //actualFirstLog.Append(actualFirst.batchNo.ToString() + ",");
  418. //actualFirstLog.Append(actualFirst.heatNo.ToString() + ",");
  419. //actualFirstLog.Append(actualFirst.shipmentNum.ToString() + ",");
  420. actualFirstLog.Append(actualFirst.matterNo.ToString() + ",");
  421. actualFirstLog.Append(actualFirst.receivingUintNo.ToString() + ",");
  422. actualFirstLog.Append(actualFirst.forwardingUnitNo.ToString() + ",");
  423. //actualFirstLog.Append(actualFirst.customerSupplierName.ToString() + ",");
  424. //actualFirstLog.Append(actualFirst.loadPointName.ToString() + ",");
  425. actualFirstLog.Append(actualFirst.memo.ToString() + ",");
  426. actualFirstLog.Append(actualFirst.weightType.ToString() + ",");
  427. actualFirstLog.Append(actualFirst.meterWeight.ToString());
  428. logCsv.WriteDataLog("actualFirst", actualFirstLog.ToString());
  429. }
  430. /// <summary>
  431. /// 上传数据
  432. /// </summary>
  433. private void uploadData()
  434. {
  435. openFileDialogUpData.Filter = "csv文件|*.csv";//只允许csv文件;*.csv;*.xlsx
  436. openFileDialogUpData.Title = "选择要导入的计量数据文件"; //弹出框头部显示
  437. openFileDialogUpData.AddExtension = true; //自动增加后缀
  438. openFileDialogUpData.AutoUpgradeEnabled = true; //是否随系统自动升级弹出窗口样式
  439. openFileDialogUpData.InitialDirectory = Application.StartupPath + "\\alonData\\" + DateTime.Now.ToString("yyyy-MM-dd");//默认打开当前目录
  440. //openFileDialog1.Multiselect = true;//该值确定是否可以选择多个文件
  441. if (openFileDialogUpData.ShowDialog() == DialogResult.OK)
  442. {
  443. DataTable csvDataTable = OpenCSV(openFileDialogUpData.FileName);
  444. int rowCount = csvDataTable.Rows.Count;
  445. if (csvDataTable != null && csvDataTable.Rows.Count > 0)
  446. {
  447. List<MeterWorkCarActualFirst> lp = csvDataTable.TableToDataList<MeterWorkCarActualFirst>();
  448. DialogResult dr = MessageBox.Show("共 " + lp.Count + " 条计量数据,是否继续上传?", "提示", MessageBoxButtons.OKCancel);
  449. if (dr != DialogResult.OK)
  450. {
  451. return;
  452. }
  453. //操作日志
  454. RESTfulResult<string> rES = actualFirstService.addEmergency(lp);
  455. if (rES.Succeed)
  456. {
  457. MessageBox.Show("数据上传成功!");
  458. }
  459. else
  460. {
  461. MessageBox.Show("数据上传失败:" + rES.Message);
  462. }
  463. }
  464. };
  465. }
  466. public static DataTable OpenCSV(string filePath)
  467. {
  468. Encoding encoding = Encoding.UTF8; //Common.GetType(filePath); //Encoding.ASCII;//
  469. DataTable dt = new DataTable();
  470. FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
  471. //StreamReader sr = new StreamReader(fs, Encoding.UTF8);
  472. StreamReader sr = new StreamReader(fs, encoding);
  473. //string fileContent = sr.ReadToEnd();
  474. //encoding = sr.CurrentEncoding;
  475. //记录每次读取的一行记录
  476. string strLine = "";
  477. //记录每行记录中的各字段内容
  478. string[] aryLine = null;
  479. string[] tableHead = null;
  480. //标示列数
  481. int columnCount = 0;
  482. //标示是否是读取的第一行
  483. bool IsFirst = true;
  484. //逐行读取CSV中的数据
  485. while ((strLine = sr.ReadLine()) != null)
  486. {
  487. //strLine = Common.ConvertStringUTF8(strLine, encoding);
  488. //strLine = Common.ConvertStringUTF8(strLine);
  489. if (IsFirst == true)
  490. {
  491. tableHead = strLine.Split(',');
  492. IsFirst = false;
  493. columnCount = tableHead.Length;
  494. //创建列
  495. for (int i = 0; i < columnCount; i++)
  496. {
  497. DataColumn dc = new DataColumn(tableHead[i]);
  498. //DataColumn dc = new DataColumn(i.ToString());
  499. dt.Columns.Add(dc);
  500. switch (i) { }
  501. }
  502. }
  503. else
  504. {
  505. aryLine = strLine.Split(',');
  506. DataRow dr = dt.NewRow();
  507. for (int j = 0; j < columnCount; j++)
  508. {
  509. dr[j] = aryLine[j];
  510. }
  511. dt.Rows.Add(dr);
  512. }
  513. }
  514. //if (aryLine != null && aryLine.Length > 0)
  515. //{
  516. // dt.DefaultView.Sort = tableHead[0] + " " + "asc";
  517. //}
  518. sr.Close();
  519. fs.Close();
  520. return dt;
  521. }
  522. /// <summary>
  523. /// 数据查询
  524. /// </summary>
  525. private void doQuery()
  526. {
  527. if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd")) == true
  528. && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv") == true)
  529. {
  530. DataTable csvDataTable = OpenCSV(AppDomain.CurrentDomain.BaseDirectory + "alonData\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\actualFirst.csv");
  531. int rowCount = csvDataTable.Rows.Count;
  532. if (csvDataTable != null && csvDataTable.Rows.Count > 0)
  533. {
  534. List<MeterWorkCarActFirAlon> lp = csvDataTable.TableToDataList<MeterWorkCarActFirAlon>();
  535. rowCount = lp.Count;
  536. //毛重数据查询
  537. DataTable dtGross = csvDataTable.Clone();
  538. List<MeterWorkCarActFirAlon> lpGross = lp.Where(s => s.weightType == "0").ToList();
  539. if (lpGross != null && lpGross.Count > 0)
  540. {
  541. dtGross = lpGross.ListToDataTable<MeterWorkCarActFirAlon>();
  542. }
  543. ClsControlPack.CopyDataToDatatable(ref dtGross, ref this.dtCarActFirstGross, true);
  544. foreach (var item in this.ultraGridGross.Rows)
  545. {
  546. item.Cells["weightType"].Value = GetWeightType(item.Cells["weightType"].Value.ToString());
  547. }
  548. ClsControlPack.RefreshAndAutoSize(ultraGridGross);
  549. //皮重数据查询
  550. DataTable dtTare = csvDataTable.Clone();
  551. List<MeterWorkCarActFirAlon> lpTare = lp.Where(s => s.weightType == "1").ToList();
  552. if (lpTare != null && lpTare.Count > 0)
  553. {
  554. dtTare = lpTare.ListToDataTable<MeterWorkCarActFirAlon>();
  555. }
  556. ClsControlPack.CopyDataToDatatable(ref dtTare, ref this.dtCarActFirstTare, true);
  557. foreach (var item in this.ultraGridTare.Rows)
  558. {
  559. item.Cells["weightType"].Value = GetWeightType(item.Cells["weightType"].Value.ToString());
  560. }
  561. ClsControlPack.RefreshAndAutoSize(ultraGridTare);
  562. }
  563. }
  564. else
  565. {
  566. MessageBox.Show("未查询到当天的数据文件!");
  567. }
  568. }
  569. /// <summary>
  570. /// 重量类型
  571. /// </summary>
  572. /// <param name="strCode"></param>
  573. /// <returns></returns>
  574. public static string GetWeightType(string strCode)
  575. {
  576. string weightType = ""; //重量类型(0:毛重;1:皮重)
  577. switch (strCode)
  578. {
  579. case "0": weightType = "毛重"; break;
  580. case "1": weightType = "皮重"; break;
  581. default:
  582. break;
  583. }
  584. return weightType;
  585. }
  586. /// <summary>
  587. /// 记录错误日志
  588. /// </summary>
  589. /// <param name="str"></param>
  590. private void WriteCatchLog(string str)
  591. {
  592. try
  593. {
  594. string m_szRunPath = System.Environment.CurrentDirectory.ToString();
  595. if (!(System.IO.Directory.Exists(m_szRunPath + "\\log")))
  596. {
  597. System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
  598. }
  599. string strDate = System.DateTime.Now.ToString("yyyyMMddhh");
  600. System.IO.TextWriter tw = new System.IO.StreamWriter(m_szRunPath + "\\log\\catch.log", true);
  601. tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + str);
  602. tw.Close();
  603. }
  604. catch
  605. {
  606. }
  607. }
  608. /// <summary>
  609. /// 保存物料信息到csv文件
  610. /// </summary>
  611. /// <param name="result"></param>
  612. private void saveMatterInfo(RESTfulResult<List<MeterBaseMatterInfo>> result)
  613. {
  614. StringBuilder materInfoHead = new StringBuilder(); // 物料头
  615. materInfoHead.Append("matterNo,");//若第一行默认为当前时间则第一行多个逗号
  616. materInfoHead.Append("matterName");
  617. logCsv.WriteBaseData("MeterBaseMatterInfo", materInfoHead.ToString());
  618. if (result.Succeed)
  619. {
  620. StringBuilder materInfo = new StringBuilder(); // 物料体
  621. List<MeterBaseMatterInfo> list = result.Data;
  622. foreach (MeterBaseMatterInfo info in list)
  623. {
  624. materInfo.Clear();
  625. materInfo.Append(info.matterNo + ",");
  626. materInfo.Append(info.matterName + ",");
  627. logCsv.WriteBaseData("MeterBaseMatterInfo", materInfo.ToString());
  628. }
  629. }
  630. }
  631. /// <summary>
  632. /// 保存收发货单位信息到csv文件
  633. /// </summary>
  634. /// <param name="result"></param>
  635. private void saveCustomerInfo(RESTfulResult<List<MeterBaseCustomerSupplier>> result)
  636. {
  637. StringBuilder customerInfoHead = new StringBuilder(); // 客商头
  638. customerInfoHead.Append("customerSupplierNo,");//若第一行默认为当前时间则第一行多个逗号
  639. customerInfoHead.Append("customerSupplierName");
  640. logCsv.WriteBaseData("MeterBaseCustomerSupplier", customerInfoHead.ToString());
  641. if (result.Succeed)
  642. {
  643. StringBuilder customerInfo = new StringBuilder(); // 物料体
  644. List<MeterBaseCustomerSupplier> list = result.Data;
  645. if(result.Data != null)
  646. {
  647. foreach (MeterBaseCustomerSupplier info in list)
  648. {
  649. customerInfo.Clear();
  650. customerInfo.Append(info.customerSupplierNo + ",");
  651. customerInfo.Append(info.customerSupplierName + ",");
  652. logCsv.WriteBaseData("MeterBaseCustomerSupplier", customerInfo.ToString());
  653. }
  654. }
  655. }
  656. }
  657. /// <summary>
  658. /// 保存计量点信息到csv文件
  659. /// </summary>
  660. /// <param name="result"></param>
  661. private void saveSpotInfo(RESTfulResult<List<MeterBaseSpotInfo>> result)
  662. {
  663. StringBuilder spotInfoHead = new StringBuilder(); // 客商头
  664. spotInfoHead.Append("spotNo,");//若第一行默认为当前时间则第一行多个逗号
  665. spotInfoHead.Append("spotName");
  666. logCsv.WriteBaseData("MeterBaseSpotInfo", spotInfoHead.ToString());
  667. if (result.Succeed)
  668. {
  669. StringBuilder spotInfo = new StringBuilder(); // 物料体
  670. List<MeterBaseSpotInfo> list = result.Data;
  671. if (result.Data != null)
  672. {
  673. foreach (MeterBaseSpotInfo info in list)
  674. {
  675. spotInfo.Clear();
  676. spotInfo.Append(info.baseSpotNo + ",");
  677. spotInfo.Append(info.baseSpotName + ",");
  678. logCsv.WriteBaseData("MeterBaseSpotInfo", spotInfo.ToString());
  679. }
  680. }
  681. }
  682. }
  683. /// <summary>
  684. /// 从csv文件读取物料信息
  685. /// </summary>
  686. /// <returns></returns>
  687. private DataTable selectMatterInfo()
  688. {
  689. if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
  690. && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv") == true)
  691. {
  692. string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseMatterInfo.csv";
  693. DataTable csvDataTable = OpenCSV(path);
  694. int rowCount = csvDataTable.Rows.Count;
  695. if (csvDataTable != null && csvDataTable.Rows.Count > 0)
  696. {
  697. DataTable newCsvDataTable = new DataTable();
  698. newCsvDataTable.Columns.Add("name");
  699. newCsvDataTable.Columns.Add("value");
  700. for (int i = 1; i < csvDataTable.Rows.Count; i++)
  701. {
  702. DataRow dr = newCsvDataTable.NewRow();
  703. dr[0] = "[" + csvDataTable.Rows[i]["matterNo"].ToString() + "]" + csvDataTable.Rows[i]["matterName"].ToString();
  704. dr[1] = csvDataTable.Rows[i]["matterNo"].ToString();
  705. newCsvDataTable.Rows.Add(dr);
  706. }
  707. return newCsvDataTable;
  708. }
  709. else
  710. {
  711. return null;
  712. }
  713. }
  714. else
  715. {
  716. return null;
  717. }
  718. }
  719. /// <summary>
  720. /// 从csv文件读取收发货单位信息
  721. /// </summary>
  722. /// <returns></returns>
  723. private DataTable selectCustomerInfo()
  724. {
  725. if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
  726. && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv") == true)
  727. {
  728. string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseCustomerSupplier.csv";
  729. DataTable csvDataTable = OpenCSV(path);
  730. int rowCount = csvDataTable.Rows.Count;
  731. if (csvDataTable != null && csvDataTable.Rows.Count > 0)
  732. {
  733. DataTable newCsvDataTable = new DataTable();
  734. newCsvDataTable.Columns.Add("name");
  735. newCsvDataTable.Columns.Add("value");
  736. for (int i = 1; i < csvDataTable.Rows.Count; i++)
  737. {
  738. DataRow dr = newCsvDataTable.NewRow();
  739. dr[0] = "[" + csvDataTable.Rows[i]["customerSupplierNo"].ToString() + "]" + csvDataTable.Rows[i]["customerSupplierName"].ToString();
  740. dr[1] = csvDataTable.Rows[i]["customerSupplierNo"].ToString();
  741. newCsvDataTable.Rows.Add(dr);
  742. }
  743. return newCsvDataTable;
  744. }
  745. else
  746. {
  747. return null;
  748. }
  749. }
  750. else
  751. {
  752. return null;
  753. }
  754. }
  755. /// <summary>
  756. /// 从csv文件读取计量点信息
  757. /// </summary>
  758. /// <returns></returns>
  759. private DataTable selectSpotInfo()
  760. {
  761. if (System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData") == true
  762. && System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv") == true)
  763. {
  764. string path = AppDomain.CurrentDomain.BaseDirectory + "baseData\\MeterBaseSpotInfo.csv";
  765. DataTable csvDataTable = OpenCSV(path);
  766. int rowCount = csvDataTable.Rows.Count;
  767. if (csvDataTable != null && csvDataTable.Rows.Count > 0)
  768. {
  769. DataTable newCsvDataTable = new DataTable();
  770. newCsvDataTable.Columns.Add("name");
  771. newCsvDataTable.Columns.Add("value");
  772. for (int i = 1; i < csvDataTable.Rows.Count; i++)
  773. {
  774. DataRow dr = newCsvDataTable.NewRow();
  775. dr[0] = "[" + csvDataTable.Rows[i]["spotNo"].ToString() + "]" + csvDataTable.Rows[i]["spotName"].ToString();
  776. dr[1] = csvDataTable.Rows[i]["spotNo"].ToString();
  777. newCsvDataTable.Rows.Add(dr);
  778. }
  779. return newCsvDataTable;
  780. }
  781. else
  782. {
  783. return null;
  784. }
  785. }
  786. else
  787. {
  788. return null;
  789. }
  790. }
  791. }
  792. }