| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645 |
- 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<String, String> 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, String>();
- }
- 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<String, Boolean> uploadHistoryDict;
- private void uploadFile(string dstFileName)
- {
- Console.WriteLine(DateTime.Now.ToString() + " uploadFile:" + dstFileName);
- //通过接口上传文件
- //整一个map,保存上传记录,上传状态
- if (uploadHistoryDict == null)
- {
- uploadHistoryDict = new Dictionary<String, Boolean>();
- }
- 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<String, String> data = new Dictionary<string, string>();
- // 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);
- }
- }
- }
- }
|