sohotcall

Mosquitto debian, NodeJS mqtt

Jun 3rd, 2021 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-the-mosquitto-mqtt-messaging-broker-on-debian-9
  2. http://www.steves-internet-guide.com/topic-restriction-mosquitto-configuration/
  3. =========
  4. MOSQUITTO
  5. =========
  6. Install
  7. -------
  8. $ sudo apt update
  9. $ sudo apt install mosquitto mosquitto-clients
  10. --------------------------
  11. Configure password and SSL
  12. --------------------------
  13. $ sudo mosquitto_passwd -c /etc/mosquitto/passwd sammy
  14. $ sudo nano /etc/mosquitto/conf.d/default.conf
  15. allow_anonymous false
  16. password_file /etc/mosquitto/passwd
  17. acl_file /etc/mosquitto/aclfile
  18. listener 1883 localhost
  19. listener 8883
  20. certfile /etc/letsencrypt/live/mqtt.example.com/cert.pem
  21. cafile /etc/letsencrypt/live/mqtt.example.com/chain.pem
  22. keyfile /etc/letsencrypt/live/mqtt.example.com/privkey.pem
  23. $ sudo nano /etc/mosquitto/aclfile
  24. #anonymous user
  25. topic read $SYS/#
  26. #user sammy (#=any topic)
  27. user sammy
  28. topic readwrite #
  29. #all client (%c = client id, %u = user)
  30. pattern readwrite %u/#
  31. $ sudo ufw allow 8883
  32. $ sudo systemctl restart mosquitto
  33. $ mosquitto_sub -h mqtt.example.com -p 8883 --capath /etc/ssl/certs/ -t "test/topic" -u "sammy" -P "password"
  34. $ mosquitto_pub -h mqtt.example.com -p 8883 --capath /etc/ssl/certs/ -t "test/topic" -m "hello world" -u "sammy" -P "password"
  35.  
  36. https://stackoverflow.com/questions/62299097/nodejs-connect-to-mqtt-server-with-credentials-and-ssl
  37. ------
  38. NodeJS
  39. ------
  40. $ npm install mqtt --save
  41. const mqtt = require( 'mqtt' )
  42. const fs = require( 'fs' )
  43. const client = new mqtt.connect( 'mqtts://' + SERVERNAME, {
  44. rejectUnauthorized: false,
  45. username: SERVERUSERNAME,
  46. password: SERVERPASSWORD,
  47. // port: 8883
  48. connectTimeout: 5000,
  49. ca: [ fs.readFileSync( MYCAFILENAME ) ],
  50. cert: fs.readFileSync( MYCERTFILENAME ),
  51. key: fs.readFileSync( MYKEYFILENAME )
  52. } )
  53. client.on( 'connect', () => {
  54. console.log( 'connected' )
  55. client.subscribe( TOPIC, ( err ) => {
  56. console.log( 'subscribed' )
  57. if ( ! err ) {
  58. client.publish( TOPIC, "hello world" )
  59. }
  60. } )
  61. } )
  62. client.on( 'message', function( topic, msg ){
  63. console.log( msg.toString() )
  64. client.end()
  65. } )
  66.  
Add Comment
Please, Sign In to add comment