5 years, 8 months ago.

Can a Mail Queue be altered to send different types of messages?

Can a Mail Queue be altered to send different types of messages?

Altered from RTOS Handbook Page

#include "mbed.h"
#include "rtos.h"

/* Mail */
typedef struct {
	uint32_t MessageType; /* Message type, 1 for Message from Temp Sensor and 2 for Messages from Accelerometer*/
	float    Temperature; /* Message Type 1 measures temperature */
} mail_MessageTypeTemperature;

typedef struct {
	uint32_t MessageType; /* Message type, 1 for Message from Temp Sensor and 2 for Messages from Accelerometer*/
	float    x; /* x Axis */
	float    y; /* y Axis */
	float    z; /* z Axis */
} mail_MessageTypeAccelerometer;

// Problem Line
Mail<mail_t, 16> mail_box;
// Problem Line

void TemperatureThread(void const *argument) {
	while (1==1)
	{
		mail_MessageTypeTemperature *mail = mail_box.alloc(); // Allocate message space
		mail->MessageType = 1; // Set Message Type
		mail->Temperature = MeasureTemperature(); // Get Temperature and place in message
		mail_box.put(mail);
		Thread::wait(1000);
	}
}
void AccelerometerThread(void const *argument) {
	while (1 == 1)
	{
		mail_MessageTypeAccelerometer *mail = mail_box.alloc(); // Allocate message space
		mail->MessageType = 2; // Set Message Type
		mail->x = GetAccelerometerX(); // Get X
		mail->y = GetAccelerometerY(); // Get Y
		mail->z = GetAccelerometerZ(); // Get Z
		mail_box.put(mail);
		Thread::wait(50);
	}
}

int main(void) {
	Thread thread(send_thread);

	while (true) {
		osEvent evt = mail_box.get();
		if (evt.status == osEventMail) {
			mail_t *mail = (mail_t*)evt.value.p;
			if (mail->MessageType == 1)
			{
				printf("\nTemperature: %.2f\n\r", mail->Temperature);
			}
			if (mail->MessageType == 2)
			{
				printf("\nTemperature: %.2f %.2f %.2f\n\r", mail->x, mail->y, mail->z);
			}
			mail_box.free(mail);
		}
	}
}

1 Answer

5 years, 6 months ago.

The way to handle this is through a union type. This way the mailbox is large enough to contain the largest message. You then need to pull the values based on the MessageType received.