Skip to content

Commit

Permalink
Исправил прослушивание порта и убрал лишнее действие в Dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
Кирилл committed Apr 1, 2019
1 parent 198f943 commit cc11b71
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 44 deletions.
2 changes: 1 addition & 1 deletion CashCode.Net/CashCode.Net/CashCode.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<Description>Библиотека работы с купюроприемником Bill Validator with Stacker</Description>
<Authors>Strukachev D., Tikhonov K.</Authors>
<Copyright>Copyright © Strukachev D. 2010</Copyright>
<Version>1.1.0</Version>
<Version>1.2.0</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
74 changes: 53 additions & 21 deletions CashCode.Net/CashCode.Net/CashCodeBillValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,8 @@ private void Dispose(bool disposing)
// Если disposing=true, освободим все управляемые и неуправляемые ресурсы
if (disposing)
{
// Отприм сигнал выключения на купюроприемник
if (_IsConnected)
{
DisableBillValidator();
}
// Здесь освободим управляемые ресурсы
_Listener.Dispose();
_IsListening = false;
_ComPort.Dispose();
}

Expand Down Expand Up @@ -460,7 +455,7 @@ private bool CheckPollOnError(byte[] ByteResult)


// Отправка команды купюроприемнику
private byte[] SendCommand(BillValidatorCommands cmd, byte[] Data = null)
private byte[] SendCommand(BillValidatorCommands cmd, byte[] data = null)
{
if (cmd == BillValidatorCommands.ACK || cmd == BillValidatorCommands.NAK)
{
Expand All @@ -478,25 +473,29 @@ private byte[] SendCommand(BillValidatorCommands cmd, byte[] Data = null)
Package package = new Package();
package.Cmd = (byte)cmd;

if (Data != null) { package.Data = Data; }
if (data != null) { package.Data = data; }

byte[] CmdBytes = package.GetBytes();
this._ComPort.Write(CmdBytes, 0, CmdBytes.Length);

// Подождем пока получим данные с ком-порта
this._SynchCom.WaitOne(EVENT_WAIT_HANDLER_TIMEOUT);
var timeout = !this._SynchCom.WaitOne(EVENT_WAIT_HANDLER_TIMEOUT);
this._SynchCom.Reset();

byte[] ByteResult = this._ReceivedBytes.ToArray();
if (timeout)
throw new TimeoutException();

// Если CRC ок, то проверим четвертый бит с результатом
// Должны уже получить данные с ком-порта, поэтому проверим CRC
if (ByteResult.Length == 0 || !Package.CheckCRC(ByteResult))
if (_packet == null || !Package.CheckCRC(_packet))
{
throw new ArgumentException(CashCode.Net.Properties.Resource.SendCommand_TheMismatchOfTheChecksumOfTheReceivedMessageTheDeviceMayNotBeConnectedToTheCOMPortCheckYourConnectionSettings);
}

return ByteResult;
var res = _packet;
_packet = null;

return res;
}

}
Expand All @@ -513,6 +512,8 @@ private byte[] SendCommand(BillValidatorCommands cmd, byte[] Data = null)
{ 0x0d, 2000 }, // 2000 р.
{ 0x07, 5000 } // 5000 р.
};
private byte[] _packet;
private readonly object _dataSyncRoot = new object();

#endregion

Expand Down Expand Up @@ -583,18 +584,49 @@ private void OnBillException(BillExceptionEventArgs e)
// Получение данных с ком-порта
private void _ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Заснем на 100 мс, дабы дать программе получить все данные с ком-порта
Thread.Sleep(100);
this._ReceivedBytes.Clear();

// Читаем байты
while (_ComPort.BytesToRead > 0)
lock (_dataSyncRoot)
{
this._ReceivedBytes.Add((byte)_ComPort.ReadByte());
// Читаем байты
while (_ComPort.BytesToRead > 0)
{
this._ReceivedBytes.Add((byte)_ComPort.ReadByte());
}

CheckPacket();
}
}

// Снимаем блокировку
this._SynchCom.Set();
private void CheckPacket()
{
var start = _ReceivedBytes.IndexOf(0x2);
if (start >= 0)
{
var lng = start + 2;
if (_ReceivedBytes.Count < lng + 1)
return;

int length = _ReceivedBytes[lng];
if (length == 0)
{
var lngHigh = lng + 2;
var lngLow = lng + 3;

/// исправить если требуется суб команда

length = lngHigh;
length = length << 8;
length = length | lngLow;
}

if (_ReceivedBytes.Count < start + length)
return;

_packet = _ReceivedBytes.Skip(start).Take(length).ToArray();
_ReceivedBytes.Clear();

// Снимаем блокировку
this._SynchCom.Set();
}
}

// Таймер прослушки купюроприемника
Expand Down
43 changes: 22 additions & 21 deletions CashCode.Net/CashCode.Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,35 @@ class Program
{
static int Sum = 0;

static CashCodeBillValidator c = new CashCodeBillValidator("COM4", 9600);


static void Main(string[] args)
{
try
{
using (CashCodeBillValidator c = new CashCodeBillValidator(CashCode.Test.Properties.Settings.Default.Port, 9600))
{
c.BillReceived += new BillReceivedHandler(c_BillReceived);
c.BillStacking += new BillStackingHandler(c_BillStacking);
c.BillCassetteStatusEvent += new BillCassetteHandler(c_BillCassetteStatusEvent);
c.BillException += new BillExceptionHandler(c_BillException);
c.ConnectBillValidator();

if (c.IsConnected)
{
c.PowerUpBillValidator();
c.StartListening();
c.BillReceived += new BillReceivedHandler(c_BillReceived);
c.BillStacking += new BillStackingHandler(c_BillStacking);
c.BillCassetteStatusEvent += new BillCassetteHandler(c_BillCassetteStatusEvent);
c.BillException += new BillExceptionHandler(c_BillException);
c.ConnectBillValidator();

if (c.IsConnected)
{
c.PowerUpBillValidator();
c.StartListening();

c.EnableBillValidator();
Console.ReadKey();
c.DisableBillValidator();
Console.ReadKey();
c.EnableBillValidator();
Console.ReadKey();
c.StopListening();
}

c.Dispose();
c.EnableBillValidator();
Console.ReadKey();
c.DisableBillValidator();
Console.ReadKey();
c.EnableBillValidator();
Console.ReadKey();
c.StopListening();
}

c.Dispose();
}
catch (Exception ex)
{
Expand Down Expand Up @@ -77,6 +77,7 @@ static void c_BillReceived(object Sender, BillReceivedEventArgs e)
static void c_BillException(object Sender, BillExceptionEventArgs e)
{
Console.WriteLine(e.Message);
c.Dispose();
}


Expand Down
2 changes: 1 addition & 1 deletion CashCode.Net/CashCode.Test/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit cc11b71

Please sign in to comment.