-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathOpenBal.cs
More file actions
247 lines (208 loc) · 7.28 KB
/
OpenBal.cs
File metadata and controls
247 lines (208 loc) · 7.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// ***********************************************************************
// Assembly : OpenAC.Net.Balanca
// Author : Marcos Gerene
// Created : 11-09-2021
//
// Last Modified By : RFTD
// Last Modified On : 11-09-2021
// ***********************************************************************
// <copyright file="OpenBal.cs" company="OpenAC .Net">
// The MIT License (MIT)
// Copyright (c) 2014-2022 Projeto OpenAC .Net
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Threading;
using System.Threading.Tasks;
using OpenAC.Net.Core;
using OpenAC.Net.Core.Extensions;
using OpenAC.Net.Devices;
namespace OpenAC.Net.Balanca;
/// <summary>
/// Classe base abstrata para comunicação com balanças.
/// </summary>
public abstract class OpenBal : OpenDisposable
{
#region Fields
/// <summary>
/// Protocolo de comunicação utilizado.
/// </summary>
private ProtocoloBalanca protocolo;
/// <summary>
/// Token para cancelamento do monitoramento.
/// </summary>
private CancellationTokenSource cancelamento;
/// <summary>
/// Stream do dispositivo conectado.
/// </summary>
private OpenDeviceStream device;
/// <summary>
/// Instância do protocolo base utilizado.
/// </summary>
private ProtocoloBase bal;
#endregion Fields
#region Eventos
/// <summary>
/// Evento lançado ao ler o peso.
/// </summary>
public event EventHandler<BalancaEventArgs> AoLerPeso;
#endregion Eventos
#region Constructors
/// <summary>
/// Inicializa uma nova instância da classe <see cref="OpenBal"/>.
/// </summary>
/// <param name="device">Configuração do dispositivo.</param>
internal OpenBal(IDeviceConfig device)
{
Protocolo = ProtocoloBalanca.Toledo;
Device = device;
}
#endregion Constructors
#region Properties
/// <summary>
/// Configuração do dispositivo.
/// </summary>
public IDeviceConfig Device { get; }
/// <summary>
/// Protocolo de comunicação utilizado.
/// </summary>
public ProtocoloBalanca Protocolo
{
get => protocolo;
set
{
if (Conectado) throw new OpenException("Não pode mudar o protocolo quando esta conectado.");
protocolo = value;
}
}
/// <summary>
/// Indica se o monitoramento está ativo.
/// </summary>
public bool IsMonitorar { get; set; }
/// <summary>
/// Delay entre as leituras de monitoramento (em milissegundos).
/// </summary>
public int DelayMonitoramento { get; set; }
/// <summary>
/// Obtém se está ou não conectado na balança.
/// </summary>
public bool Conectado => device != null && device.Conectado;
#endregion Properties
#region Methods
/// <summary>
/// Método para conectar na balança.
/// </summary>
/// <exception cref="OpenException">Lançada se a porta já estiver aberta ou protocolo não suportado.</exception>
public void Conectar()
{
if (Conectado) throw new OpenException("A porta já está aberta");
if (!Enum.IsDefined(typeof(ProtocoloBalanca), Protocolo)) throw new OpenException(@"Protocolo não suportado.");
// Controle de porta não serve para balança.
Device.ControlePorta = false;
device = OpenDeviceFactory.Create(Device);
device.Open();
switch (Protocolo)
{
case ProtocoloBalanca.Toledo:
bal = new ProtocoloToledo(device);
break;
case ProtocoloBalanca.Filizola:
bal = new ProtocoloFilizola(device);
break;
default:
throw new ArgumentOutOfRangeException();
}
cancelamento = new CancellationTokenSource();
Monitorar();
}
/// <summary>
/// Método para desconectar da balança.
/// </summary>
/// <exception cref="OpenException">Lançada se a porta não estiver aberta.</exception>
public void Desconectar()
{
if (!Conectado) throw new OpenException("A porta não está aberta");
cancelamento?.Cancel();
device?.Close();
device?.Dispose();
device = null;
bal = null;
}
/// <summary>
/// Solicita a leitura do peso à balança.
/// </summary>
/// <returns>Peso lido.</returns>
/// <exception cref="OpenException">Lançada se a conexão não estiver ativa.</exception>
public decimal LerPeso()
{
if (device == null) throw new OpenException("A conexão não esta ativa.");
var monitorando = IsMonitorar;
try
{
IsMonitorar = false;
bal.LePeso();
AoLerPeso?.Raise(this, new BalancaEventArgs(bal.UltimaResposta, bal.UltimoPesoLido));
}
catch (Exception ex)
{
AoLerPeso?.Raise(this, new BalancaEventArgs(bal.UltimaResposta, ex));
}
finally
{
IsMonitorar = monitorando;
}
return bal.UltimoPesoLido;
}
/// <summary>
/// Inicia o monitoramento assíncrono da balança.
/// </summary>
private async void Monitorar()
{
await Task.Run(async () =>
{
while (!cancelamento.IsCancellationRequested)
{
//Não o while mesmo com o IsMonitorar false, porque pode ser uma para momentânea para uma requisição manual
if (!IsMonitorar) continue;
try
{
bal.LePeso();
//bal.LeSerial();
AoLerPeso?.Raise(this, new BalancaEventArgs(bal.UltimaResposta, bal.UltimoPesoLido));
}
catch (Exception ex)
{
AoLerPeso?.Raise(this, new BalancaEventArgs(bal.UltimaResposta, ex));
}
finally
{
await Task.Delay(DelayMonitoramento);
}
}
}, cancelamento.Token);
}
/// <inheritdoc />
protected override void DisposeManaged()
{
if (Conectado)
Desconectar();
}
#endregion Methods
}