Как определить глобальный байт чтения / записи - PullRequest
0 голосов
/ 08 апреля 2020

Я разрабатываю программу формы windows, которая управляет цифровыми входами и выходами программно, как PL C.

Мой план состоит в том, чтобы иметь состояния входов и выходные данные доступны между классами, которые управляют фактическим оборудованием, и основной программой GUI.

Мой план состоит в том, чтобы иметь переменную List или, возможно, байтовую переменную, которая находится «глобально» и может быть прочитана и записана, но У меня проблемы с определением - я посмотрел на синглтоны и глобальные переменные, которые люди сказали избегать. Вот моя текущая, очень грубая архитектура:

public partial class Form1 : Form
{
    BrainBoxes BB;

    public static List<int> Outputs; //How do I define this to allow reading and writing from the Brainboxes Class?

    public Form1()
    {
        InitializeComponent();
        BB = new BrainBoxes();

    }

    private void Button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }


    private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int I_Line = 0; //this will be dynamic in the future, for now it is static for testing
        int O_Line = 0; //this will by dynamic in the future
        while (backgroundWorker1.CancellationPending == false)
        {
            var Inputs = BB.ReadInputs(); // obtain the current state of the input module.
            if (Inputs[I_Line] == 1) { Outputs[O_Line] = 1; } //currently we get a NullReference Exception
            else if(Inputs[I_Line] == 0) { Outputs[O_Line] = 0; }
            BB.SetOutputs(Outputs); //set all outputs to their new states.
            Thread.Sleep(50);
        }
    }

    private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("Program Completed");
    }
}

    public class BrainBoxes //this is the class which communicates and controls the physical equipment. 
{
    EDDevice ED527;
    EDDevice ED516;



    public BrainBoxes() // set up devices and connections to all devices connected in the constructor
    {

        ED527 = EDDevice.Create("192.168.127.1");
        ED516 = EDDevice.Create("192.168.127.2");

        ED527.Connect(); // connect to each device in sequence. 
        ED516.Connect();

    }

    public void SetOutputs(List<int> arr)
    {
    // Loop through the List received and set the lines in/out respectively
        int index = 0;
        foreach(int i in arr)
        { 
            if (i == 0) { DIO_0(index); }
            else { DIO_1(index); }
            index++;
        }
    }

    public List<int> ReadInputs()
    {
    //read each input and return a list.
        List<int> Inputs = new List<int>();
        for(int i = 0; i < 16; i++)
        {
            Inputs.Add(ED516.Inputs[i].Value);
        }
        return Inputs;
    }
    public void DIO_0(int i)
    {
    //Set an output to off
        ED527.Outputs[i].Value = 0;
    }
    public void DIO_1(int i)
    {
    //set an output to on.
        ED527.Outputs[i].Value = 1;
    }
}

Может ли кто-нибудь помочь в выборе наилучшего подхода к структурированию списка выходов? Извиняюсь, если это кажется глупым вопросом - я по образованию инженер-механик.

...