I’m currently running a test on an IoT project which is utilizing AWS IOT Core service. I have an MQTT broker with a Thing set up to which I have connection policies defined and authentication access certificates generated. Using these with a policy defined ClientID, I’m able to successfully publish project’s sensors data(i.e temperature, humidity, soil pH and ambient light values) to the MQTT broker using Raspberry pi pico(RP2040) microcontroller device.
From the broker, I’ve set up DynamoDB database tables to which the received data at the broker level is consumed. Then using NodeJs APIs listener, the data is fetched for display in a NodeJs web application in realtime. All these so far works well.
However, my actual problem kicks in whenever I try to publish data(set threshold values) from the platform to the MQTT broker using the very same topic to which the RP2040 device is publishing. Immediately whenever the platform published data is received at the broker, device published data stops being received by the broker.
Here’s the API for handling platform publishing of DHT sensor threshold:
// -----------Publish to broker---------------
// DHT sensor component threshold
router.get('/dht-threshold-mqtt-publish', async (req, res) => {
console.log("nData Publishing ---------------------------");
try {
const { project_id, user_id } = req.query;
// Fetch data from MongoDB based on project_id and user_id
const dhtSensorData = await DHTSensor.findOne({ project_id, user_id });
if (!dhtSensorData) {// validate if data isa available
return res.status(404).json({ success: false, message: 'DHTSensor data not found' });
}
// Extract the temp_threshold from the retrieved data
const tempThreshold = dhtSensorData.temp_threshold.toString();
const humidThreshold = dhtSensorData.humid_threshold.toString();
console.log("Component: DHTnPublished thresholds;n -Temperature: "+tempThreshold+"n -Humidity: "+humidThreshold);
// Construct the JSON payload
const jsonPayload = JSON.stringify({
user_id: user_id.toString(),
project_id: project_id.toString(),
dht_temperature_threshold: tempThreshold,
dht_humidity_threshold: humidThreshold,
});
// call MQTT setup
await mqttDataPublishHandler(jsonPayload, 'DHTSensor', res);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false, message: 'Internal server error' });
}
});
And the publishing function handler:
// MQTT broker data publish handler
async function mqttDataPublishHandler(dataPayload, targetComponent, res) {
const mqttBrokerUrl = process.env.MQTT_BROKER_URL; // MQTT broker URL
const topic = process.env.MQTT_PUB_TOPIC;
const clientId = process.env.MQTT_CLIENT_ID; // Set your unique client_id
console.log("MQTT broker url: ", mqttBrokerUrl);
const mqttOptions = {
clientId: clientId,
protocol: 'mqtts', // Use 'mqtts' for MQTT over TLS/SSL
rejectUnauthorized: true, // Set to "false" to ignore certificate validation (for testing only)
key: fs.readFileSync(process.env.MQTT_CLIENT_KEY_PATH), // Set path to your client key
cert: fs.readFileSync(process.env.MQTT_CLIENT_CERT_PATH), // Set path to your client certificate
ca: fs.readFileSync(process.env.MQTT_CA_CERT_PATH), // Set path to your CA certificate
};
const mqttClient = mqtt.connect(mqttBrokerUrl, mqttOptions);
let responseSent = false;
mqttClient.on('error', (err) => {
if (!responseSent) {
console.error('MQTT Connection Error:', err);
res.status(500).json({ success: false, message: 'MQTT Connection Error' });
responseSent = true;
}
});
mqttClient.on('connect', () => {
// Publish payload to the specified MQTT topic
mqttClient.publish(topic, dataPayload.toString(), (err) => {
if (!responseSent) {
if (err) {
console.error('MQTT Publish Error:', err);
res.status(500).json({ success: false, message: 'MQTT Publish Error' });
} else {
console.log(targetComponent+" threshold data published to MQTT broker.");
// Close the MQTT connection
mqttClient.end();
// Respond to the client
res.json({ success: true, data: dataPayload });
}
responseSent = true;
}
});
});
}
Does this mean AWS IoT thing can’t support multi-device publishing to a common topic and so I should consider creating a topic under Many Things?
At initial stage of experiencing this, I thought it could be due to creation of concurrent connections to MQTT broker from different endpoints(platform API and from device firmware). I resolved this by ensuring platform connection to broker is only initiated at the time a new sensor threshold value is being set and thereafter close the connection.
However, this did not resolve the issue.`
Any assistance kindly in case you’ve come across this? Thank you.