public bool ReadTai(AslTaiData data) { return WriteTaiInternal(data, false).Result; }
private async Task<bool> WriteTaiInternal(AslTaiData data, bool write) { if (!Connected) return false; if (data is AslQuitTai) { //Just write the data because we will never hear back _sw.WriteLine(data.GetWriteCommand()); return true; } Busy = true; var token = _tokenSource.Token; var delayTask = Task.Delay((int)data.Timeout, token); string command = write ? data.GetWriteCommand() : data.GetReadCommand(); var readTask = Task.Factory.StartNew(() => TaiBounce(command, token)); var finishedTask = await Task.WhenAny(delayTask, readTask); if (finishedTask == delayTask) { //We timed out. Abort the read _tokenSource.Cancel(); Busy = false; return false; } else { //Get a list of valid tokens List<string> tokens = new List<string>(); tokens.AddRange(Misc.Tokens); foreach (AslTaiData d in CustomCommands) tokens.Add(d.GetReadCommand().Substring(0, 2)); //Find the relevant data foreach (string tokenString in tokens) { List<int> dataLocs = FindRelevantData(readTask.Result, tokenString); //Parse the data foreach (int loc in dataLocs) { string l = readTask.Result[loc]; //Extract the ID string id = l.Substring(4, 4); foreach (Asl a in Devices) { //Check to see if the responding ASL matches the ASL we are looking at via the loop if ((a.Id == id) || (a.Id == "0000")) { List<AslTaiData> parseObjects = new List<AslTaiData>(); parseObjects.AddRange(CustomCommands); parseObjects.AddRange(a.DataObjects); //Find the specific command this mapped to for (int i = 0; i < parseObjects.Count; ++i) { //Get a pointer to the current command object we are looking at via the loop AslTaiData t = parseObjects[i]; //Get the command ID from the string received from the TAI string cmdId = l.Substring(10, 2); //Does the received ID match the ID of the command we are looking at via the loop? if (cmdId == t.GetCommandID()) { //Create an instance of an IcParams-type command object so we can get its command string AslIcParams ic = new AslIcParamsNoLoop(); //Does the command received have to do with a control loop? if (cmdId == ic.GetCommandID()) { //Special handling for this: must cast as appropriate type ic.Parse(l); //Cast t as the appropriate inherited object switch (ic.Loop) { case LoopControl.Co2YLoop: t = new AslIcParamsCo2Y(); break; case LoopControl.ConstantMvLoop: t = new AslIcParamsConstMv(); break; case LoopControl.ConstantVtLoop: t = new AslIcParamsConstVt(); break; default: t = new AslIcParamsNoLoop(); break; } } //Update the object based on the data received lock (t) { t.Parse(l); } break; } } } } HandleExceptions(); } } } HandleExceptions(); Busy = false; return true; }
public bool WriteTai(AslTaiData data) { return WriteTaiInternal(data, true).Result; }