电子称 弹钱箱脉冲

try
{

if (this.serialPort1.IsOpen)
{
Thread.Sleep(300);

      int num = port1.BytesToRead;
      char[] readchar = new char[num];
      port1.Read(readchar, 0, num);
      string str="";
      for (int i = 0; i < 4; i++)//readchar.Length 4位 读取前4位 还有6位的情况
      {
      str += readchar[i].ToString();
      }

      return str;

}
}
catch (Exception ex)
{

}

public double GetWeight()
{
//权限
//明细
//是否可以称重
try
{
Posset posset = SystemConfig.getPosset();
Printerset printerSet = pl.GetPrintersetList(posset.PosCode).First();
SerialPort sPort = new SerialPort(printerSet.scalesComPort, printerSet.scalesBaudRate.Value, Parity.None, printerSet.scalesDataBits.Value, (StopBits)printerSet.scalesStopBits.Value);
serialPortControl = new SerialPortControl(sPort, port1_datareceived);
serialPortControl.OpenPort();
serialPortControl.SendCommand("$");
Stools.MyLognet.WriteInfo(weight.ToString());
return weight;
}
catch (Exception ex)
{
Stools.MyLognet.WriteInfo("打开端口失败" + ex.Message+DateTime.Now.ToString());
ModernDialog.ShowMessage("打开端口失败", "提示", System.Windows.MessageBoxButton.OK);
return 0;
}
}

private void port1_datareceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort port1 = serialPortControl.port1;
StringBuilder currentline = new StringBuilder();
if (port1.IsOpen)
{
Thread.Sleep(500);
while (port1.BytesToRead > 0)
{
char ch = (char)port1.ReadByte();
currentline.Append(ch);
}
string[] currentWeight = currentline.ToString().Split(' ');
if (!string.IsNullOrEmpty(currentWeight[1]))
{
weight =ArithUtil.div(Double.Parse(currentWeight[1]),1000);
// Stools.MyLognet.WriteInfo(weight.ToString());
}
else
{
return;
}
}
serialPortControl.ClosePort();
}
catch (Exception ex)
{
Stools.MyLognet.WriteInfo("电子秤读取失败" + ex.Message + DateTime.Now.ToString());
ModernDialog.ShowMessage("电子秤读取失败", "提示", System.Windows.MessageBoxButton.OK);
}
finally {
serialPortControl.ClosePort();
}
}

 

 

 

 

 

 

 

using FirstFloor.ModernUI.Windows.Controls;
using qxsaas.Nhibernate.SubEntity;
using qxsaas.Services.BLL.Impl;
using qxsaas.util;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows;

namespace qxsaas.Util
{
/// <summary>
/// 并口打印
/// </summary>
public class LPTPrinter
{
#region StructLayout

[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
int Internal;
int InternalHigh;
int Offset;
int OffSetHigh;
int hEvent;
}

[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName,
uint dwDesiredAccess,
int dwShareMode,
int lpSecurityAttributes,
int dwCreationDisposition,
int dwFlagsAndAttributes,
int hTemplateFile
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile,
byte[] lpBuffer,
int nNumberOfBytesToWrite,
ref int lpNumberOfBytesWritten,
ref OVERLAPPED lpOverlapped
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject
);
#endregion
string _Lpt = "";

public LPTPrinter()
{ }

public LPTPrinter(string lpt)
{
this._Lpt = lpt;
}
private int iHandle;
Printerset printerSet = null;
PrintLogic pl = new PrintLogic();
/// <summary>
/// 打开并口
/// </summary>
/// <returns></returns>
public bool Open()
{
iHandle = CreateFile(this._Lpt, 0x50000000, 0, 0, 3, 0, 0);
if (iHandle != -1)
{
return true;
}
else
{
return false;
}
}

/// <summary>
/// 获取打印机状态
/// </summary>
/// <returns></returns>
public int GetHandle()
{
return iHandle;
}

/// <summary>
/// 打印字符串
/// </summary>
/// <param name="Mystring"></param>
/// <returns></returns>
public bool Write(String Mystring)
{
try
{
Open();
if (iHandle != -1)
{
OVERLAPPED x = new OVERLAPPED();
int i = 0;

byte[] mybyte = System.Text.Encoding.Default.GetBytes(Mystring);
bool b = WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
return b;
}
else
{
//throw new Exception("不能连接到打印机!");
Stools.MyLognet.WriteWarn("打印字符串不能连接到打印机!");
return false;
}
}
catch (Exception ex)
{
Stools.MyLognet.WriteError("打印字符串异常!");
Stools.MyLognet.WriteError("Message :\n" + ex.Message + "StackTrace :\n" + ex.StackTrace);
return false;
}
finally { Close(); }


}
/// <summary>
/// 向并口发送数据
/// </summary>
/// <param name="mybyte"></param>
/// <returns></returns>
public bool Write(byte[] mybyte)
{
try
{
if (iHandle != -1)
{
OVERLAPPED x = new OVERLAPPED();
int i = 0;
WriteFile(iHandle, mybyte, mybyte.Length, ref i, ref x);
//MovePaper();
return true;
}
else
{
//throw new Exception("不能连接到打印机!");
Stools.MyLognet.WriteWarn("向并口发送数据不能连接到打印机!");
return false;
}
}
catch(Exception ex)
{
Stools.MyLognet.WriteError("向并口发送数据异常!");
Stools.MyLognet.WriteError("Message :\n" + ex.Message + "StackTrace :\n" + ex.StackTrace);
return false;
}
}

/// <summary>
/// 关闭并口
/// </summary>
/// <returns></returns>
public bool Close()
{
return CloseHandle(iHandle);
}

/// <summary>
/// 脉冲弹钱箱(单一)
/// </summary>
/// <returns></returns>
public bool PopCashbox()
{
//this.Write(new byte[] { 0x1B, 0x70 });
//#27+#112+#0+#100+#100
//"" + (char)(27) + 'p' + (char)(0) + (char)(60) + (char)(255);
//return this.Write(new byte[] { 0x1B, 0x70 });
//CHR(27)+ 'p'+ CHR(0)+'<'+ CHR(255)
//"" + (char)(27) + 'p' + (char)(0) + (char)(60) + (char)(255)
printerSet = pl.GetPrintersetList(posset.PosCode)[0];
string cashPort = printerSet.cashPort != null ? printerSet.cashPort : "LPT1";
string cashCom = printerSet.cashCmd != null ? printerSet.cashCmd : "" + (char)(27) + 'p' + (char)(0) + (char)(60) + (char)(255);
_Lpt=cashPort;
return this.Write(cashCom);
}

/// <summary>
/// 走纸
/// </summary>
/// <param name="line">行数</param>
/// <returns></returns>
public bool MovePaper(byte line)
{
return this.Write(new byte[] { 0x1B, 0x64, line });
}

#region [ 电子称 ]
SerialPortControl serialPortControl;
string weight;
Posset posset = SystemConfig.getPosset();

public string GetEndWeight()
{
GetWeight();
if (weight!="")
{
return weight;
}
return "";
}


bool isDataRe = false;
public void GetWeight()
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
//权限
//明细
//是否可以称重
try
{
printerSet = pl.GetPrintersetList(posset.PosCode)[0];
int sc = printerSet.scalesFlag == 1 ? 1 : 0;
if (sc != 1)
{
ModernDialog.ShowMessage("电子称没启用请启用并设置参数!", "提示", System.Windows.MessageBoxButton.OK);
}
}
catch (Exception ex)
{
Stools.MyLognet.WriteInfo("读取打印设置失败!");
}

try
{

SerialPort sPort = new SerialPort(printerSet.scalesComPort, printerSet.scalesBaudRate.Value, Parity.None, printerSet.scalesDataBits.Value, (StopBits)printerSet.scalesStopBits.Value);
serialPortControl = new SerialPortControl(sPort, port1_datareceived);
serialPortControl.OpenPort();
serialPortControl.SendCommand("$");
DateTime dt = DateTime.Now;
while (!isDataRe)
{
Thread.Sleep(500);
if ((DateTime.Now - dt).TotalSeconds > 3)
break;
}
}
catch (Exception ex)
{
Stools.MyLognet.WriteInfo("打开端口失败" + ex.Message + DateTime.Now.ToString());
ModernDialog.ShowMessage("打开端口失败", "提示", System.Windows.MessageBoxButton.OK);
}
}));

}

private void port1_datareceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
SerialPort port1 = serialPortControl.port1;
StringBuilder currentline = new StringBuilder();

if (port1.IsOpen)
{
Thread.Sleep(500);
while (port1.BytesToRead > 0)
{
char ch = (char)port1.ReadByte();
currentline.Append(ch);
}
string[] currentWeight = currentline.ToString().Split(' ');
if (!string.IsNullOrEmpty(currentWeight[1]))
{
weight = currentWeight[1];
//Stools.MyLognet.WriteInfo("weight: " + weight[0]);
isDataRe = true;
}
else
{

}
}
serialPortControl.ClosePort();
}
catch (Exception ex)
{
Stools.MyLognet.WriteInfo("电子秤读取失败" + ex.Message);
ModernDialog.ShowMessage("电子秤读取失败", "提示", System.Windows.MessageBoxButton.OK);
}
finally { serialPortControl.ClosePort(); }

}

#endregion [电子称]

#region [ 弹钱箱 ]
string tempprintStr;
public Printerset getprinterSet()
{
try
{
if (CacheUtil.printerset == null || SystemConfig.getRefreshFlagForBaseData(ParamContant.syncparam8))
{
PrintLogic printlogic2 = new PrintLogic();
IList<Printerset> psList = printlogic2.GetPrintersetList();
if (psList.Count > 0 && psList != null)
{
Printerset pst = psList[0];
CacheUtil.printerset = pst;

}
}
return CacheUtil.printerset;
}
catch (Exception ex)
{

//ModernDialog.ShowMessage("加载打印参数失败 请检查网络连接!" + ex.Message, "提示", MessageBoxButton.OK);
return null;
}
}
/// <summary>
/// 弹出钱箱
/// </summary>
/// <returns>0:操作成功,1端口错误或找不到钱箱,2:设置错误,3其他错误</returns>
public void outDrawer()
{
printerSet = getprinterSet();
try
{
if (printerSet.printOutDrawer == 1)
{
switch (printerSet.portType)
{
case 0: //com口
#region portType=0
try
{
if (printerSet.comPort.Equals(printerSet.cashPort))
{
SerialPort sPort = new SerialPort(printerSet.comPort, printerSet.baudRate.Value, (Parity)(Enum.Parse(typeof(Parity), printerSet.parity.Value + "")), printerSet.dataBits.Value, (StopBits)(Enum.Parse(typeof(StopBits), printerSet.stopBits.Value + "")));
SerialPortControl serialPortControl = new SerialPortControl(sPort, null);
try
{
int status = serialPortControl.OpenPort();
//如果打开失败
if (status == 0)
{
Stools.MyLognet.WriteError("status == 0 钱箱端口打开失败" + DateTime.Now.ToString());
// return 1;
}
//打开成功,弹出
if (!string.IsNullOrEmpty(printerSet.cashCmd))
{
string[] cashCmdArray = printerSet.cashCmd.Split(new char[] { ',' });
byte[] cmdData = new byte[cashCmdArray.Length];
for (int i = 0; i < cmdData.Length; i++)
{
string cashCmdStr = cashCmdArray[i];
byte b = Byte.Parse(cashCmdStr);
cmdData[i] = b;
}
serialPortControl.SendCommand(cmdData);

}
}
catch (Exception ex)
{
Stools.MyLognet.WriteError("Error" + ex.Message + ":" + ex.StackTrace + DateTime.Now.ToString());

}
finally
{
//无论如何都要关闭
serialPortControl.ClosePort();
}
}
}
catch (Exception)
{


}
finally
{


}

#endregion portType=0
break;
case 1: //LPT1口
#region portType1
if (string.IsNullOrEmpty(printerSet.lptPort))
{
Stools.MyLognet.WriteError("钱箱设置错误" + DateTime.Now.ToString());
// return 2;
}
POSDllUtil pdUtil = new POSDllUtil();
try
{
//PosDll打印
bool flag = pdUtil.OpenLPTPort(printerSet.lptPort);
if (flag == false)
{
//初始化打印机参数失败。请检测打印机配置。
Stools.MyLognet.WriteError("1端口错误或找不到钱箱" + DateTime.Now.ToString());
// return 1;
}
POSDllUtil.POS_KickOutDrawer(0, 100, 80);
}
catch
{
}
finally
{
//无论如何都要关闭
pdUtil.ClosePrinterPort();
}
#endregion portType=1
break;
case 2:
#region portType=2
//驱动打印 打印设置弹钱箱
outDrawerForDeiver();
#endregion portType=2
break;
case 3: //net
#region portType=3
if (string.IsNullOrEmpty(printerSet.netPort))
{
Stools.MyLognet.WriteError("1端口错误或找不到钱箱");
// return 2;
}
pdUtil = new POSDllUtil();
try
{
//PosDll打印
bool flag = pdUtil.OpenNetPort(printerSet.netPort);
if (flag == false)
{
//初始化打印机参数失败。请检测打印机配置。
Stools.MyLognet.WriteError("1端口错误或找不到钱箱");
//return 1;
}
POSDllUtil.POS_KickOutDrawer(0, 100, 80);
}
catch
{
}
finally
{
//无论如何都要关闭
pdUtil.ClosePrinterPort();
}
#endregion portType=3
break;
case 4:
#region portType=4
//名称打印
// outDrawerForDeiver();
try
{
if (printerSet.comPort.Equals(printerSet.cashPort))
{
SerialPort sPort = new SerialPort(printerSet.comPort, printerSet.baudRate.Value, (Parity)(Enum.Parse(typeof(Parity), printerSet.parity.Value + "")), printerSet.dataBits.Value, (StopBits)(Enum.Parse(typeof(StopBits), printerSet.stopBits.Value + "")));
SerialPortControl serialPortControl = new SerialPortControl(sPort, null);
try
{
int status = serialPortControl.OpenPort();
//如果打开失败
if (status == 0)
{
Stools.MyLognet.WriteError("status == 0 钱箱端口打开失败" + DateTime.Now.ToString());
}
//打开成功,弹出
if (!string.IsNullOrEmpty(printerSet.cashCmd))
{
string[] cashCmdArray = printerSet.cashCmd.Split(new char[] { ',' });
byte[] cmdData = new byte[cashCmdArray.Length];
for (int i = 0; i < cmdData.Length; i++)
{
string cashCmdStr = cashCmdArray[i];
byte b = Byte.Parse(cashCmdStr);
cmdData[i] = b;
}
serialPortControl.SendCommand(cmdData);
}
}
catch (Exception ex)
{
Stools.MyLognet.WriteError("Error" + ex.Message + ":" + ex.StackTrace + DateTime.Now.ToString());
}
finally
{
//无论如何都要关闭
serialPortControl.ClosePort();
}
}
}
catch (Exception ex)
{
Stools.MyLognet.WriteError("Error" + ex.Message + ":" + ex.StackTrace + DateTime.Now.ToString());
}
#endregion portType=4
break;
default:
#region portType 其他

#endregion portType 其他
break;
}
}
else
{
//不使用钱箱
}

}
catch (Exception ex)
{
//不使用钱箱
Stools.MyLognet.WriteError("Error" + ex.Message + ":" + ex.StackTrace + DateTime.Now.ToString());
}
}
/// <summary>
/// 弹出钱箱
/// </summary>
/// <returns>0:操作成功,1端口错误或找不到钱箱,2:设置错误,3其他错误</returns>
public int outDrawerForDeiver()
{
if (string.IsNullOrEmpty(printerSet.printName))
{
Stools.MyLognet.WriteError("驱动打印设置错误 请检测打印机配置。");
return 2;
}
bool flag = true;
if (flag == false)
{
//初始化打印机参数失败。请检测打印机配置。
Stools.MyLognet.WriteError("驱动打印 初始化打印机参数失败。请检测打印机配置。");
return 1;
}
else
{
//已经成功打开打印机
try
{
PrintDocument printDoc = new PrintDocument();
tempprintStr = "";
printDoc.PrintPage += new PrintPageEventHandler(PrintDoc_PrintPage);
printDoc.PrinterSettings.PrinterName = printerSet.printName;
System.Drawing.Printing.StandardPrintController spc = new StandardPrintController();

printDoc.PrintController = spc;
printDoc.Print();
}
catch (Exception ex)
{
Stools.MyLognet.WriteError("Error" + ex.Message + ":" + ex.StackTrace + DateTime.Now.ToString());
return 3;
}
}
return 0;
}

private void PrintDoc_PrintPage(object sender, PrintPageEventArgs e)
{
PringDouble(e.Graphics);
}
private void PringDouble(Graphics g)
{
Font fontItem = new Font("Tahoma", 7, System.Drawing.FontStyle.Regular);
SolidBrush brushItem = new SolidBrush(Color.Black);
StringFormat formatItem = new StringFormat();
formatItem.Trimming = StringTrimming.EllipsisCharacter;
g.DrawString(tempprintStr, fontItem, brushItem, 10, 15);
}

#endregion 弹钱箱
}
}

posted @ 2015-08-11 11:30  pengde  阅读(384)  评论(0编辑  收藏  举报