vendredi 15 février 2019

Socket programming with heartbeat keeps falling out of sync

I have a device I connect to via a com port and it has 3 functions:

  • Heartbeat I must Acknowledge
  • Status Check
  • Start devices operation

When the device sends a heartbeat to me, my next message to the device must always be an acknowledgement or the device won't respond.

The Problem I have is that every now and again my application will send a StartDevice or StatusCheck command just after receiving a Heartbeat and it all falls apart

How do I solve this problem?

I've written a simple version of my code below: public class MyDevice {

    ComPort comPort;
    Timer statusTimer;

    public MyDevice() {
        //Create a socket connection to the device
        comPort = new ComPort("COM5");
        comPort.Recieve += RecieveSomeData;
        comPort.Open();
        //Start an update timer every 5 mins
        statusTimer = new Timer();
        statusTimer.Tick += StatusTimerTick;
        statusTimer.Start(5);
    }

    public void StartDevice() {
        comPort.Send("Start Device Operation!");
    }

    protected void StatusTimerTick() {
        comPort.Send("What is your status?");
    }

    protected void RecieveSomeData(string data) {
        //if the device sends heart beat, send acknowledgment back
        if (data.StartsWith("Heartbeat")) {
            comPort.Send("Acknowledgement!");
        }
        //if the device is replying to status or 
        // a start operation then tell the consumer
        else {
            ReportStatus(data);
        }
    }

    private void ReportStatus(string data) {
        throw new NotImplementedException();
    }
}

Aucun commentaire:

Enregistrer un commentaire