FrmStandAloneMetering.cs 39 KB

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