public void OpenSerialPort() { _atListenThread = new Thread(ReadDataLoop); BaseSerialPort.Open(); BaseSerialPort.Encoding = Encoding.UTF8; //technically, this should be GSM but whatever _atListenThread.Start(); }
private void ReadDataLoop() { while (!RequestCancel) { var s = new StringBuilder(); var binaryWriteSignal = false; while (true) { if (RequestCancel) { return; } var c = BaseSerialPort.ReadByte(); //this will block the thread until it reads something. if (c > char.MaxValue) { logger.LogError("Read character from serial port that exceeded max char value!"); continue; } if (c < 0) { break; //means we couldn't read } if (c == '>') //we hit an input thing, need to signal to start writing. { logger.LogInformation("Received binary start symbol"); binaryWriteSignal = true; break; } if (c == ResponseFormattingCharacter) { break; } s.Append((char)c); } if (binaryWriteSignal) { //TODO: start signal if (CurrentBinaryWriteTask == null) { logger.LogWarning("Received binary write indicator but no binary write task existed!"); //throw new Exception("Binary write task was null but received start character!"); continue; } CurrentBinaryWriteTask.SetResult(true); continue; } logger.LogInformation("Received serial line: " + s.ToString().Replace("\n", "<LN>").Replace("\r", "<CR>")); var line = s.ToString().Trim(); if (string.IsNullOrEmpty(line)) { continue; } if (line.StartsWith("AT+")) { continue; //means that we are receiving what we sent (echo) } if (line == "OK" || line == "ERROR") { if (CurrentBinaryWriteTask != null) { CurrentBinaryWriteTask.SetResult(false); } else { try { AtCommandResultQueue.First.Value.SetResult(new CommandResult(line switch { "OK" => ATCommandResultCode.OK, "ERROR" => ATCommandResultCode.Error })); }
public void CloseSerialPort() { BaseSerialPort.Close(); }