Change baud rate in loop

Hey guys I have a question. I have a device that forces me to change the baud rate on the go from 115200 to 9600, send enter and then change back to 115200 again to continue communication. I tried but it seems not to change accordingly. Can anyone spot an obvious mistake in my coding?

#include <SoftwareSerial.h>

//Software-UART Pins for XBee
SoftwareSerial xbee_serial(2, 3); // RX, TX

unsigned long tmp;

//Message to announce completed initialization
char msg[] = {'\n', 'c', 'o', 'm', 'p', 'l', 'e', 't', 'e', 'd', '\n'};

void setup() {

  Serial.begin(115200);
  xbee_serial.begin(115200);
}

void loop() {

  do{
    
  //Transfer bootmessage from UniFi to XBee
  if (Serial.available()) {
    xbee_serial.write(Serial.read());
  }
  tmp = millis();
  }while (tmp < 50000); //Wait 50 sec. for the UniFi to boot
  
  //Change to 9600
  Serial.flush();
  Serial.begin(9600);

  delay(3000);

  //Send "enter"
  Serial.write('\n');

  delay(3000);
    
  //Change to 115200
  Serial.flush();
  Serial.begin(115200);

  //Message that initialization is completed
  for (int x = 0; x < 11; x++) {
  xbee_serial.write(msg[x]);
  }

  while (1) {

  //Transfer input from UniFi to XBee
  if (Serial.available()) {
    xbee_serial.write(Serial.read());
  }

  //Transfer input from XBee to UniFi
  if (xbee_serial.available()) {
    Serial.write(xbee_serial.read());
  }
 }
}
  Serial.flush();
  Serial.begin(9600);

  delay(3000);

I'd put the baud rate change the other side of the delay.

Parleoth:
I have a device that forces me to change the baud rate on the go from 115200 to 9600, send enter and then change back to 115200 again to continue communication.

I'm finding that very hard to believe, and I bet you don't, you just need a better understanding of what the hell you are doing.

Even in the unlikely event that it is true, this

  xbee_serial.begin(115200);

is not likely to fix anything, indeed it will almost certainly be fatal. Software serial is only good for 38400 and, if you must run this device at 115200, you need to put it on hardware serial.

It might be time to re-think what this project is all about - and perhaps be more forthcoming on this.

@Nick_Pynner

Strogly disagree with ability of softwareserial not to work good at 115200.

Check my topic and code.
https://forum.arduino.cc/index.php?topic=544577.0

Its running perfect at 115200.

Good for you. Never having used, or needed to use, Software Serial myself, I won't bother asking why you can do it yet so many others on this forum have nothing but grief, and I don't think it is a good idea to put a newbie behind the 8-ball. And I did say "not likely to..."

I understand that there are versions of software serial other than "Software serial" that perform better, but I don't know if they might be up to the job in hand.

dev?