Advertisement
Guest User

mariadbmqtt

a guest
Aug 19th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1.  
  2. var mqtt = require('mqtt');
  3. var Topic = '#'; //subscribe to all topics
  4. var Broker_URL = 'mqtt://192.168.1.123';
  5. var Database_URL = '192.168.1.123';
  6.  
  7. var options = {
  8. clientId: 'MyMQTT',
  9. port: 1883,
  10. //username: 'mqtt_user',
  11. //password: 'mqtt_password',
  12. keepalive : 60
  13. };
  14.  
  15. var client = mqtt.connect(Broker_URL, options);
  16. client.on('connect', mqtt_connect);
  17. client.on('reconnect', mqtt_reconnect);
  18. client.on('error', mqtt_error);
  19. client.on('message', mqtt_messsageReceived);
  20. client.on('close', mqtt_close);
  21.  
  22. function mqtt_connect() {
  23. //console.log("Connecting MQTT");
  24. client.subscribe(Topic, mqtt_subscribe);
  25. }
  26.  
  27. function mqtt_subscribe(err, granted) {
  28. console.log("Subscribed to " + Topic);
  29. if (err) {console.log(err);}
  30. }
  31.  
  32. function mqtt_reconnect(err) {
  33. //console.log("Reconnect MQTT");
  34. //if (err) {console.log(err);}
  35. client = mqtt.connect(Broker_URL, options);
  36. }
  37.  
  38. function mqtt_error(err) {
  39. //console.log("Error!");
  40. //if (err) {console.log(err);}
  41. }
  42.  
  43. function after_publish() {
  44. //do nothing
  45. }
  46.  
  47. function mqtt_messsageReceived(topic, message, packet) {
  48. //console.log('Message received = ' + message);
  49. insert_message(topic, message, packet);
  50. }
  51.  
  52. function mqtt_close() {
  53. //console.log("Close MQTT");
  54. }
  55.  
  56. ////////////////////////////////////////////////////
  57. ///////////////////// MYSQL ////////////////////////
  58. ////////////////////////////////////////////////////
  59. var mysql = require('mysql');
  60.  
  61. //Create Connection
  62. var connection = mysql.createConnection({
  63. host: Database_URL,
  64. user: "newuser",
  65. password: "mypassword",
  66. database: "mydb"
  67. });
  68.  
  69. connection.connect(function(err) {
  70. if (err) throw err;
  71. //console.log("Database Connected!");
  72. });
  73.  
  74. //insert a row into the tbl_messages table
  75. function insert_message(topic, message, packet) {
  76. var clientID= "client001";
  77. var sql = "INSERT INTO ?? (??,??,??) VALUES (?,?,?)";
  78. var params = ['tbl_messages', 'clientID', 'topic', 'message', clientID, topic, message];
  79. sql = mysql.format(sql, params);
  80. connection.query(sql, function (error, results) {
  81. if (error) throw error;
  82. console.log("1 record inserted");
  83. });
  84. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement