Advertisement
Guest User

Untitled

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