Skip to content

lgiuliani80/iothub-mqtt-client-test-nodejs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TestMQTT - Node.js MQTTS Client

A Node.js application for connecting to MQTTS brokers with support for Azure IoT Hub integration, client certificates, and comprehensive logging.

Description

This application provides a robust MQTTS client that can connect to MQTT brokers using SSL/TLS encryption. It includes special support for Azure IoT Hub connections with automatic SAS token generation, twin operations, and device-to-cloud messaging.

Features

  • ✅ MQTTS (MQTT over SSL/TLS) connection support
  • ✅ Azure IoT Hub integration with SAS token authentication
  • ✅ Client certificate authentication
  • ✅ Device Twin operations (GET)
  • ✅ Device-to-cloud messaging
  • ✅ Cloud-to-device message reception
  • ✅ Comprehensive event logging
  • ✅ Configurable connection parameters
  • ✅ Automatic test message publishing

Installation

  1. Clone or download the project
  2. Install dependencies:
    npm install

Usage

Basic MQTTS Connection

node app.js --host <mqtt_host> --device-id <device_id> [options]

Azure IoT Hub Connection

node app.js --iothub <iothub_name> --device-id <device_id> --device-key <device_key> --host <iothub_host>

Command Line Options

Required Parameters

  • --host <string> - MQTT hostname or IP address
  • --device-id <string> - Device identifier

Azure IoT Hub Parameters

NOTE: omit those parameters if not connecting to Azure IoT Hub, but to a generic MQTT server.

  • --iothub <string> - IoT Hub name (automatically configures username and generates SAS token) - this is required for Azure IoT Hub connections and shall NOT include the .azure-devices.net suffix.
  • --device-key <string> - Shared access key for IoT Hub device

Connection Parameters

NOTE: these parameters are not required for Azure IoT Hub connections.

  • --port <number> - MQTTS broker port (default: 8883)
  • --username <string> - Username for MQTT connection
  • --password <string> - Password for MQTT connection
  • --mqtt-version-int <number> - MQTT protocol version (default: 4)

Security Parameters

NOTE: these parameters are not required for Azure IoT Hub connections.

  • --cert <string> - Path to client certificate file
  • --key <string> - Path to client private key file
  • --ca <string> - Path to Certificate Authority file
  • --reject-unauthorized <boolean> - Verify broker certificate validity (default: false)

Usage Examples

1. Connect to Azure IoT Hub

node app.js --iothub myiothub --device-id mydevice001 --device-key "devkey" --host myiothub.azure-devices.net

2. Connect with Client Certificates

node app.js --host mqtt.example.com --device-id sensor01 --cert client.pem --key client.key --ca root_ca.pem --reject-unauthorized true

3. Basic MQTTS Connection with Username/Password

node app.js --host secure-mqtt.example.com --device-id device123 --username myuser --password mypassword --port 8883

4. Connect to Local MQTTS Broker

node app.js --host localhost --device-id testdevice --username admin --password secret --port 8883

Environment Variables

You can also use environment variables for sensitive information:

  • IOTHUB_DEVICE_KEY - Device key for Azure IoT Hub. Alternative to --device-key parameter
  • MQTT_PASSWORD - MQTT password - alternative to --password parameter - NOT required for Azure IoT Hub connections

Example:

set IOTHUB_DEVICE_KEY=omissis
node app.js --iothub myiothub --device-id mydevice001 --host myiothub.azure-devices.net

Azure IoT Hub Integration

When using the --iothub parameter, the application automatically:

  1. Generates SAS Token: Creates a Shared Access Signature token for authentication
  2. Configures Username: Sets the proper username format for Azure IoT Hub
  3. Subscribes to Twin Updates: Listens for device twin changes ($iothub/twin/res/#)
  4. Requests Twin State: Sends a GET request for the current twin state
  5. Subscribes to C2D Messages: Listens for cloud-to-device messages
  6. Sends Test Messages: Publishes test events every 20 seconds

Twin Operations

The application automatically subscribes to twin response topics and sends a twin GET request:

Topic: $iothub/twin/GET/?$rid=1

Device-to-Cloud Messages

Test messages are published to:

Topic: devices/{device-id}/messages/events/
Payload: {"kind": "TestMessage", "time": "2025-01-07T10:30:00.000Z"}

Cloud-to-Device Messages

The application subscribes to:

Topic: devices/{device-id}/messages/devicebound/#

Logging

The application provides comprehensive logging for:

  • Connection events (connect, reconnect, close, offline, error, end)
  • Message events (message, packetsend, packetreceive)
  • Subscription confirmations
  • Publication results
  • Error conditions

All events are logged with timestamps and detailed information.

File Structure

testmqtt/
├── app.js                # Main application file
├── build-iothub-sas.js   # SAS token generation utility
├── package.json          # Project dependencies
└── README.md             # This file

Dependencies

  • mqtt: MQTT client library
  • yargs: Command-line argument parsing
  • crypto: Cryptographic functionality (built-in Node.js)
  • fs: File system operations (built-in Node.js)

Troubleshooting

Connection Issues

  1. Certificate Errors: Ensure certificate files are valid and accessible
  2. Authentication Failures: Verify username/password or device key
  3. Network Issues: Check host and port accessibility
  4. Protocol Version: Try different MQTT protocol versions if connection fails

License

This project is provided as-is for educational and testing purposes.

Contributing

Feel free to submit issues and enhancement requests!

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published