using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; using System.IO; using Saraff.Tiff; using Saraff.Tiff.Core; using Saraff.Twain; using HXX.Scanner.Client.Base; using HXX.Scanner.Client.Properties; using HXX.Scanner.Biz; using HXX.Scanner.Common; namespace HXX.Scanner.Client { public partial class frmMain : BaseForm { public frmMain() { //Font = new Font(Font.Name, 8.25f * 96f / CreateGraphics().DpiX, Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont); CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } private void frmMain_Load(object sender, EventArgs e) { showDataDir(); this.lblInstallPath.Text = Application.StartupPath; st = new ScanTool(); if (!biz_socketServer.Start(Settings.Default.webSocket_url)) { MsgManager.Error("服务开启失败,请检查"); } } ScanTool st = null; StringBuilder uploadFailMsgs = new StringBuilder(); private void lblRefreshDevice_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (!config_environment.loading) { config_environment.loading = true; loadScannerByTwain(); config_environment.loading = false; } } private async void loadScannerByTwain() { updateUIOLoadingState(true); await loadScannerByTwainAsync(); updateUIOLoadingState(false); } private void updateUIOLoadingState(Boolean loading) { if (loading) { this.loadSB.Visible = true; } else { this.loadSB.Visible = false; if (this.cmbDeviceList.Items.Count == 0) { MessageBox.Show(this, "没有加载到扫描仪", "提示"); } } } private Task loadScannerByTwainAsync() { return Task.Run(() => { if (st != null) { try { var result_scan = this._twain32.OpenDSM(); scanner_manager.Clear(); for (int i = 0; i < this._twain32.SourcesCount; i++) { //TODO 判断设备类型,有可能把摄像头给加载进来了// 支持2.0及以上的,才加载进来 if (this._twain32.GetIsSourceTwain2Compatible(i)) { var sc = new Device_Scanner(this._twain32.GetSourceProductName(i)) { dsIndex = i }; scanner_manager.Add(sc); } } InitScannerCombobox(); } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString() + " loadScannerByTwainAsync got exception" + ex); } } }); } private static void loadScannerProperty(Device_Scanner scanner) { try { String manufacturer = scanner.manufacturer; String config = ""; if (manufacturer.Contains("CANON")) { config = Properties.Settings.Default.CannonConfig; //TODO } else if (manufacturer.Contains("Panasonic")) { config = Properties.Settings.Default.PanasonicConfig; } else if (manufacturer.Contains("Kodak"))//Eastman Kodak { config = Properties.Settings.Default.KodakConfig; } else if (manufacturer.Contains("Epson")) { config = Properties.Settings.Default.PanasonicConfig; } else if (manufacturer.Contains("HP")) { config = Properties.Settings.Default.PanasonicConfig; } else if (manufacturer.Contains("HUAGO")) { config = Properties.Settings.Default.PanasonicConfig; } if (config != null && config.Length > 0) { string[] configItems = config.Split(';'); foreach (string configItem in configItems) { string[] configItemArr = configItem.Split('='); if (configItemArr.Length == 2) { if (configItemArr[0].Equals("ld")) { int ld = Int32.Parse(configItemArr[1]); scanner.ld = ld; } if (configItemArr[0].Equals("dbd")) { scanner.dbd = Int32.Parse(configItemArr[1]); } if (configItemArr[0].Equals("zz")) { //scanner.setPaperSize(biz_property_engine_to_scanner.get_paper_byIndex(Int32.Parse(configItemArr[1]))); } } }; } } catch (Exception ee) { LogManager.WriteLog(ee); } } private void InitScannerCombobox() { this.cmbDeviceList.SelectedIndexChanged -= new System.EventHandler(this.cmbDeviceList_SelectedIndexChanged); this.cmbDeviceList.DataSource = scanner_manager.Scanner_List; this.cmbDeviceList.DisplayMember = "deviceName"; this.cmbDeviceList.ValueMember = "dsIndex"; this.cmbDeviceList.SelectedIndexChanged += new System.EventHandler(this.cmbDeviceList_SelectedIndexChanged); if (this.cmbDeviceList.Items.Count > 0) { this.cmbDeviceList.SelectedIndex = 0; } } private void lblTestA_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { config_environment.scan_type = ScanType.Test_Panel_1_Side; config_environment.scan_ab = false; config_environment.paper_size = PaperSize.A4; Scan(); } catch (Exception ee) { LogManager.WriteLog(ee); MsgManager.Error("扫描出错。"); } } private void lblTestAB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { config_environment.scan_type = ScanType.Test_Panel_2_Sides; config_environment.scan_ab = true; config_environment.paper_size = PaperSize.A4; Scan(); } catch (Exception ee) { LogManager.WriteLog(ee); MsgManager.Error("扫描出错。"); } } private void Scan() { if (st != null) { if (this.cmbDeviceList.SelectedItem != null) { if (!string.IsNullOrEmpty(Settings.Default.dataDir)) { Device_Scanner scanner = (Device_Scanner)this.cmbDeviceList.SelectedItem; if (scanner.openSourceReady) { if (scanner.isTwain) { config_environment.scan_state = true; //biz_property_scanner_to_engine.Scan(this._twain32, scanner); } else { //if (config_environment.testScanOn) { st.test(Properties.Settings.Default.dataDir, scanner, "5"); } } } else { MsgManager.Warn("未正常连接扫描仪"); } } else { MsgManager.Warn("请先设置数据存放位置"); } } else { MsgManager.Warn("请选择扫描设备"); } } } private void lblChangeDir_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { changeDataDir(); } private void changeDataDir() { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择扫描数据存放位置"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (string.IsNullOrEmpty(dialog.SelectedPath)) { MessageBox.Show(this, "存放位置不能为空", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); } else { Settings.Default.dataDir = dialog.SelectedPath; Settings.Default.Save(); showDataDir(); } } } private void showDataDir() { lblDataPath.Text = Settings.Default.dataDir; lblDiskLeft.Text = biz_disk.getDataDirLeftSpace(Settings.Default.dataDir); } #region twain events private void _twain32_AcquireCompleted(object sender, EventArgs e) { Console.WriteLine(DateTime.Now.ToString() + " 4 扫描完成" + e.ToString()); config_environment.scan_state = false; } private void _twain32_AcquireError(object sender, Saraff.Twain.Twain32.AcquireErrorEventArgs e) { //扫描出错It worked String msg = biz_twainException.get_TwainException_msg(e.Exception); LogManager.WriteLog(msg); if (msg.Contains("It worked")) { Console.WriteLine("_twain32_AcquireError 扫描结束"); } else { Console.WriteLine(DateTime.Now.ToString() + " _twain32_AcquireError 扫描出错" + msg); } config_environment.scan_state = false; } private void _twain32_DeviceEvent(object sender, Saraff.Twain.Twain32.DeviceEventEventArgs e) { Console.WriteLine(DateTime.Now.ToString() + " 这个方法没有调用过 设备事件" + e.ToString()); } private void _twain32_EndXfer(object sender, Saraff.Twain.Twain32.EndXferEventArgs e) { Console.WriteLine(DateTime.Now.ToString() + " _twain32_EndXfer 这个方法实际没有调用,因为保持扫描文件方式不是那个啥 进度完成" + e.ToString()); } IDictionary filePageMarkerDict; int batchFileCount = 0; string uniquePageMarker = ""; //每一个批次上传的临时标记,uniquePageMarker使用 private string getDataDir() { String baseDir = Properties.Settings.Default.dataDir + "/"; if (false == System.IO.Directory.Exists(baseDir)) { System.IO.Directory.CreateDirectory(baseDir); } //String dataDir = baseDir + "/" + examId + "-" + examPaperId + "-" + zipId; String dataDir = baseDir + "/"; if (false == System.IO.Directory.Exists(dataDir)) { System.IO.Directory.CreateDirectory(dataDir); } return dataDir; } private void _twain32_SetupFileXferEvent(object sender, Saraff.Twain.Twain32.SetupFileXferEventArgs e) { e.FileName = @"d:\1\" + DateTime.Now.ToString("MMddHHmmssfff") + ".tif"; Console.WriteLine(DateTime.Now.ToString() + " 1 设置文件进度事件" + e.ToString()); if (checkCancel(e)) { try { //if (config_environment.testScanOn) //{ // e.FileName = Settings.Default.dataDir + "\\" + string.Format(@"测试{0}.{1}", DateTime.Now.ToString("MMddHHmmssfff"), this._twain32.Capabilities.ImageFileFormat.GetCurrent().ToString().ToLower()); //} //else { //正式扫描,要新建examId,examPaperId,zipId文件夹 String dir = this.getDataDir(); e.FileName = dir + "\\" + string.Format(@"{0}.{1}", DateTime.Now.ToString("MMddHHmmssfff"), this._twain32.Capabilities.ImageFileFormat.GetCurrent().ToString().ToLower()); //通过接口上传文件 //整一个map,保存上传记录,上传状态 if (filePageMarkerDict == null) { filePageMarkerDict = new Dictionary(); } string fnameTemp = Path.GetFileName(e.FileName); fnameTemp = fnameTemp.Substring(0, fnameTemp.Length - 1); batchFileCount++; if (config_environment.scan_ab) { //双面 if (batchFileCount % 2 == 0) { //反面 filePageMarkerDict.Add(fnameTemp, this.uniquePageMarker + "-" + (batchFileCount - 1)); } else { //正面 filePageMarkerDict.Add(fnameTemp, this.uniquePageMarker + "-" + batchFileCount); } } else { //单面 filePageMarkerDict.Add(fnameTemp, this.uniquePageMarker + "-" + batchFileCount); } } } catch (Exception ex) { LogManager.WriteLog(ex); } } else { Console.WriteLine("has cancel"); } } private Boolean checkCancel(Twain32.SerializableCancelEventArgs e) { if (!config_environment.scan_state) { try { e.Cancel = true; } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString() + " checkCancel Exception:" + ex.Message); } } return config_environment.scan_state; } private void _twain32_XferDone(object sender, Saraff.Twain.Twain32.XferDoneEventArgs e) { //ImageInfo imageInfo = e.GetImageInfo(); Console.WriteLine(DateTime.Now.ToString() + " 2 图像传输完成" + e.ToString()); } private void _twain32_FileXferEvent(object sender, Saraff.Twain.Twain32.FileXferEventArgs e) { Console.WriteLine(DateTime.Now.ToString() + " 3 文件传输完成" + e.ToString()); //测试扫描一张 || 取消扫描 if (config_environment.scan_type != ScanType.Formal && !config_environment.scan_ab) { //测试只扫描一张(一面) try { e.Cancel = true; } catch (Exception ex) { Console.WriteLine(DateTime.Now.ToString() + " cancel Exception:" + ex.Message); } } else { Console.WriteLine("not cancle scan"); } string fileName = e.ImageFileXfer.FileName; String dstFileName = fileName; //TODO 压缩与上传,做成异步方式 if (true) { if (fileName.EndsWith(".tiff")) { dstFileName = fileName.Substring(0, fileName.Length - 1); //压缩图片 Device_Scanner.zipImage(fileName, dstFileName, true); } else if (fileName.EndsWith(".bmp")) { dstFileName = fileName.Substring(0, fileName.Length - 3) + "tif"; //压缩图片 Device_Scanner.zipImage(fileName, dstFileName, true); } //if (config_environment.testScanOn) //{ // System.Diagnostics.Process.Start("explorer.exe", Properties.Settings.Default.dataDir); //} //else { this.uploadFile(dstFileName); } } } #endregion IDictionary uploadHistoryDict; private void uploadFile(string dstFileName) { Console.WriteLine(DateTime.Now.ToString() + " uploadFile:" + dstFileName); //通过接口上传文件 //整一个map,保存上传记录,上传状态 if (uploadHistoryDict == null) { uploadHistoryDict = new Dictionary(); } uploadHistoryDict.Add(Path.GetFileName(dstFileName), false); //开始上传 goUpload(dstFileName); } private void goUpload(String filePath) { //int tryTimes = 1; //Boolean uploadSuccess = false; //while (tryTimes <= 2) //{ // Console.WriteLine(DateTime.Now.ToString() + tryTimes + " > " + filePath); // try // { // String url = Settings.Default.apiUrlBase + Settings.Default.uploadFileUrl; // //MultipartFormDataContent multiContent = new MultipartFormDataContent(); // Dictionary data = new Dictionary(); // data.Add("token", Properties.Settings.Default.token); // data.Add("examId", examId + ""); // data.Add("examPaperId", examPaperId + ""); // data.Add("zipId", zipId + ""); // data.Add("schoolId", schoolId + ""); // String uniquePageMarker = ""; // Console.WriteLine(DateTime.Now.ToString() + "filePath:" + filePath); // String fileName = Path.GetFileName(filePath); // if (filePageMarkerDict.ContainsKey(fileName)) // { // uniquePageMarker = filePageMarkerDict[fileName]; // } // Console.WriteLine("uniquePageMarker:" + uniquePageMarker + " " + fileName); // data.Add("uniquePageMarker", uniquePageMarker + ""); // data.Add("TifBase64", FileToBase64String(filePath)); // data.Add("fileName", fileName); // String result = ""; // if (false) // { // //HttpClient httpClient = new HttpClient(); // //httpClient.Timeout = TimeSpan.FromSeconds(4); // //FormUrlEncodedContent multiContent = new FormUrlEncodedContent(data); // ////接口需要判断2张图是一张答题卡的 // //Console.WriteLine(DateTime.Now.ToString() + "fileName:" + fileName); // //HttpResponseMessage response = await httpClient.PostAsync(url, multiContent); // //response.EnsureSuccessStatusCode(); // //result = await response.Content.ReadAsStringAsync(); // } // else // { // result = sendPost(url, data); // } // Console.WriteLine(DateTime.Now.ToString() + "goUpload result:" + result); // JObject jsonData = (JObject)JsonConvert.DeserializeObject(result); // int code = Int32.Parse(jsonData["code"].ToString()); // if (code == 200) // { // //上传完成后,更新为true // uploadHistoryDict[Path.GetFileName(filePath)] = true; // uploadSuccess = true; // } // else // { // Console.WriteLine(DateTime.Now.ToString() + "goUpload fail : " + jsonData["msg"].ToString()); // //MessageBox.Show(this, jsonData["msg"].ToString(), "提示"); // uploadFailMsgs.Append(jsonData["msg"].ToString()); // } // } // catch (Exception e) // { // Console.WriteLine(DateTime.Now.ToString() + "goUpload exception :" + e.Message); // } // if (uploadSuccess) // { // break; // } // else // { // tryTimes++; // } //} //if (!uploadSuccess) //{ // Console.WriteLine(DateTime.Now.ToString() + "fail this.scanState:" + this.scanState + " uploadFailTimes:" + uploadFailTimes + " fileName:" + filePath); // this.scanState = false; // uploadFailTimes++; // //stop scan // //MessageBox.Show(this, "上传扫描图片失败,请检查网络是否通畅。建议删除该批次,然后重试", "错误提示"); //} } private void cmbDeviceList_SelectedIndexChanged(object sender, EventArgs e) { var scanner = (Device_Scanner)this.cmbDeviceList.SelectedItem; scanner.openSourceReady = false; try { this._twain32.CloseDataSource(); this._twain32.SourceIndex = scanner.dsIndex; if (this._twain32.OpenDataSource()) { scanner.openSourceReady = true; scanner.Brightness = this._twain32.Capabilities.Brightness.Get(); scanner.BrightnessBaseIndex = (scanner.Brightness.Count - 1) / 2; scanner.Contrasts = this._twain32.Capabilities.Contrast.Get(); scanner.ContrastsBaseIndex = (scanner.Contrasts.Count - 1) / 2; loadScannerProperty(scanner); } } catch (TwainException te) { LogManager.WriteLog(te); MsgManager.Error(biz_twainException.get_TwainException_msg(te)); } catch (Exception ee) { LogManager.WriteLog(ee); } } } }