多次打开相同的串口

时间:2017-07-19 06:18:24

标签: c# winforms serial-port

System.dll中出现未处理的“System.UnauthorizedAccessException”类型异常 附加信息:拒绝访问端口“COM3”。 第二次打开端口时(当我再次打开此窗体时)发生错误

use JSON qw( decode_json encode_json from_json to_json );

sub dclone { from_json(to_json($_[0])) }

my $foos_by_comp = decode_json(...);

my @flattened_foos_grouped_by_comp;
for my $comp (keys(%$foos_by_comp)) {
   my @flattened_foos_of_comp;
   my $foo = $foos_by_comp->{$comp};
   for my $search_string (@{ $foo->{searchString} }) {
       my $flattened_foo = dclone($foo);
       $flattened_foo->{ comp         } = $comp;
       $flattened_foo->{ searchString } = $search_string;
       push @flattened_foos_of_comp, $flattened_foo;
   }

   push @flattened_foos_grouped_by_comp, \@flattened_foos_of_comp;
}

print(encode_json(\@flattened_foos_grouped_by_comp));

1 个答案:

答案 0 :(得分:0)

此问题的可能解决方案可能是将串行连接放在单独的类中,并在收到数据时提供事件。然后,每个窗口都可以为此事件添加事件处理程序。在下面的代码中,我试图只维护串行连接所需的部分。我无法在我的机器上尝试它,所以可能会有一些小问题。此事件也非常基本。最好定义一个满足您特定需求的委托:

public class SerialConnection
{
    INIFile settings = new INIFile("C:\\Lateco\\settings.ini");
    public SerialPort SerialPort { get; set; }
    static SerialConnection connection= null;
    public event EventHandler WeightReceived;

    public static SerialConnection OpenConnection()
    {
        if(connection == null)
        {
            connection = new SerialConnection();
            string portname, baudrate, parity, databits, stopbits, handshake;

            portname = settings.Read("SERIAL PORT PROPERTIES", "PORT_NAME");
            baudrate = settings.Read("SERIAL PORT PROPERTIES", "BAUD_RATE");
            parity = settings.Read("SERIAL PORT PROPERTIES", "PARITY");
            databits = settings.Read("SERIAL PORT PROPERTIES", "DATA_BITS");
            stopbits = settings.Read("SERIAL PORT PROPERTIES", "STOP_BITS");
            handshake = settings.Read("SERIAL PORT PROPERTIES", "HANDSHAKE");

            connection.SerialPort = new SerialPort(); //error here
            connection.SerialPort.PortName = portname;
            connection.SerialPort.BaudRate = int.Parse(baudrate);
            connection.SerialPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity, true);
            connection.SerialPort.DataBits = int.Parse(databits);
            connection.SerialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopbits, true);
            connection.SerialPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake, true);

            connection.SerialPort.Open();
            connection.SerialPort.ReadTimeout = 200;
            connection.SerialPort.DataReceived += new SerialDataReceivedEventHandler(connection.serialPort1_DataReceived);
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                weight = SerialPort.ReadExisting();
                weight = weight.Substring(0, 7);

                WeightReceived?.Invoke(weight, new EventArgs());
            }
            catch (TimeoutException) { }
        }

        return connection;
    }

    public void CloseConnection()
    {
        if (SerialPort.IsOpen)
                SerialPort.Close();
    }

    ~SerialConnection()
    {
        if (SerialPort.IsOpen)
                SerialPort.Close();
    }
}

Form中使用它:

public partial class frmAddInventoryTransItem3 : MetroForm
    {
        public frmAddInventoryTrans ReceivingAdd { set; get; }
        public frmEditInventoryTrans ReceivingEdit { set; get; }

        string inv_type2 = null, action2 = null, document2 = null;
        private string weight;
        private SerialConnection sc = null;

        private void frmAddInventoryTransItem3_Load(object sender, EventArgs e)
        {
            txtQty.Text = 1.ToString();
            txtWeight.Text = 0.ToString("N3");
            this.ActiveControl = txtPLU;

            sc = SerialConnection.OpenConnection();
            sc.WeightReceived += new SerialDataReceivedEventHandler(WeightReceived);
        }

        private void WeightReceived(object weight, EventArgs e)
        {
                weight = weight as string;

                try
                {
                    if (this.InvokeRequired)
                        this.BeginInvoke(new EventHandler(DisplayText));
                }
                catch (ObjectDisposedException) { }
        }

        private void DisplayText(object sender, EventArgs e)
        {
            txtWeight.Text = weight;
        }
    }
}