Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.65 KB | None | 0 0
  1. # Libraries
  2. import paho.mqtt.client as mqttClient
  3. import time
  4. import sys, os, json, pika
  5. import MySQLdb
  6. from datetime import datetime
  7.  
  8. # Setup Database begin
  9. # Open Database Connection
  10. db = MySQLdb.connect("localhost", "root", "password", "kelas")
  11.  
  12. # prepare a cursor object using cursor() method
  13. cursor = db.cursor()
  14.  
  15. # execute table function
  16. def eksekusi(sql, done, err):
  17. try:
  18. # Execute the SQL command
  19. cursor.execute(sql)
  20. # Commit your changes in the database
  21. db.commit()
  22. if done != " ":
  23. print done
  24. except:
  25. # Rollback in case there is any error
  26. db.rollback()
  27. if err != " ":
  28. print err
  29. #Setup Database end
  30.  
  31. '''
  32. # Kalo pake RabbitMQ local
  33. # Setup AMQP begin
  34. credentials = pika.PlainCredentials('rifqil', 'rifqil')
  35. # IP Address-nya diganti jangan lupa
  36. parameters = pika.ConnectionParameters('192.168.0.116',
  37. 5672,
  38. '/',
  39. credentials)
  40.  
  41. connection = pika.BlockingConnection()
  42. #pika.ConnectionParameters(host='192.168.0.132'))
  43. '''
  44.  
  45. # Setup AMQP begin
  46. credentials = pika.PlainCredentials('kondisiruang', 'kondisiruang')
  47. parameters = pika.ConnectionParameters('167.205.7.226',
  48. 5672,
  49. '/kondisiruang',
  50. credentials)
  51.  
  52. connection = pika.BlockingConnection(parameters)
  53. #pika.ConnectionParameters(host='192.168.0.132'))
  54.  
  55. channel = connection.channel()
  56.  
  57. channel.queue_declare(queue='holosensor',
  58. durable=True)
  59.  
  60. channel.exchange_declare(exchange='amq.topic',
  61. exchange_type='topic',
  62. durable=True
  63. )
  64. # Setup AMQP end
  65.  
  66. # Setup MQTT begin
  67. def on_connect(client, userdata, flags, rc):
  68.  
  69. if rc == 0:
  70.  
  71. print("Connected to broker")
  72.  
  73. global Connected #Use global variable
  74. Connected = True #Signal connection
  75.  
  76. else:
  77.  
  78. print("Connection failed")
  79.  
  80. def on_message(client, userdata, message):
  81. print "Message Received: " + message.payload
  82.  
  83. # Parsing JSON data
  84. json_Dict = json.loads(message.payload)
  85. Date_and_Time = (datetime.today()).strftime("%d-%b-%Y %H:%M:%S:%f")
  86. SensorID = json_Dict['SENSOR_ID']
  87. tempdata = json_Dict['TEMPERATURE']
  88. humidata = json_Dict['HUMIDITY']
  89. lightdata = json_Dict['LIGHTINTENSITY']
  90. sounddata = json_Dict['SOUNDLEVEL']
  91.  
  92. # Habis ini harus coba print dulu yang angka-angka (sensorID ke bawah) di konsol
  93.  
  94. # Prototype
  95. # Creating Recommendation
  96.  
  97. # Recommendation Temperature
  98. if (tempdata > 27.0):
  99. recomtempdata = "Suhu terlalu tinggi, buka ventilasi"
  100. elif ((tempdata >= 23.0) and (tempdata <= 27.0)):
  101. recomtempdata = "No Recommendation"
  102. elif (tempdata < 23.0):
  103. recomtempdata = "Suhu cukup rendah, tutup ventilasi"
  104.  
  105. # Recommendation Humidity
  106. if (humidata > 80.0):
  107. recomhumiddata = "Tutup Jendela"
  108. elif ((humidata >= 30.0) and (humidata <= 80.0)):
  109. recomhumiddata = "No Recommendation"
  110. elif (humidata < 30.0):
  111. recomhumiddata = "Humidity too Low"
  112.  
  113. # Recommendation Light
  114. if (lightdata > 5000):
  115. recomlightdata = "Tutup Jendela"
  116. elif (lightdata > 500) and (lightdata <= 5000):
  117. recomlightdata = "Matikan Lampu"
  118. elif (lightdata >= 300) and (lightdata <= 500):
  119. recomlightdata = "No Recommendation"
  120. elif (lightdata < 300):
  121. recomlightdata = "Nyalakan Lampu"
  122.  
  123. # Recommendation Sound
  124. if (sounddata > 45):
  125. recomsounddata = "Ruangan terlalu berisik"
  126. elif ((sounddata >= 20) and (sounddata <= 45)):
  127. recomsounddata = "No Recommendation"
  128.  
  129. # Automating the actuator
  130. # if (SensorID == 1):
  131.  
  132.  
  133. # Prepare SQL query to INSERT a record into the database.
  134. sql = "INSERT INTO holosensor1(date_n_time, sensor_id, temperature, recommend_temperature, humidity, recommend_humidity, light_intensity, recommend_light, sound_intensity, recommend_sound) \
  135. VALUES ('%s', '%d', '%lf', '%s', '%lf', '%s', '%d', '%s', '%d', '%s')" % \
  136. (Date_and_Time, SensorID, tempdata, recomtempdata, humidata, recomhumiddata, lightdata, recomlightdata, sounddata, recomsounddata)
  137. # Process Input Data to database Holosensor
  138. eksekusi (sql, "Input database Berhasil", "GAGAL")
  139.  
  140. # Initializing sensor data to be sent
  141. msgJson={}
  142. msgJson["DATE_AND_TIME"] = Date_and_Time
  143. msgJson["SENSOR_ID"] = SensorID
  144. msgJson["TEMPERATURE"] = tempdata
  145. msgJson["RECOMTEMP"] = recomtempdata
  146. msgJson["HUMIDITY"] = humidata
  147. msgJson["RECOMHUMID"] = recomhumiddata
  148. msgJson["LIGHTINTENSITY"] = lightdata
  149. msgJson["RECOMLIGHT"] = recomlightdata
  150. msgJson["SOUNDLEVEL"] = sounddata
  151. msgJson["RECOMSOUND"] = recomsounddata
  152.  
  153. # properties = pika.BasicProperties(content_type = "application/json", delivery_mode = 1)
  154.  
  155. # Sending sensor data with recommendation
  156. channel.basic_publish(exchange='amq.topic', routing_key='holosensor.data', body= json.dumps(msgJson))
  157.  
  158. Connected = False #global variable for the state of the connection
  159.  
  160. '''
  161. # Kalo connect ke RabbitMQ Local
  162. # Jangan lupa ganti IP Address
  163. broker_address= "192.168.0.116" #Broker address
  164. port = 1883 #Broker port
  165. user = "rifqil" #Connection username
  166. password = "rifqil" #Connection password
  167. '''
  168.  
  169. broker_address= "167.205.7.226" #Broker address
  170. port = 1883 #Broker port
  171. user = "/kondisiruang:kondisiruang" #Connection username
  172. password = "kondisiruang" #Connection password
  173.  
  174. client = mqttClient.Client("Raspi") #create new instance
  175. client.username_pw_set(user, password=password) #set username and password
  176. client.on_connect= on_connect #attach function to callback
  177. client.on_message= on_message #attach function to callback
  178.  
  179. client.connect(broker_address, port=port) #connect to broker
  180.  
  181. client.loop_start() #start the loop
  182. # client.loop_forever(timeout=1.0, max_packets=1, retry_first_connection=False)
  183.  
  184. while Connected != True: #Wait for connection
  185. time.sleep(0.1)
  186.  
  187. client.subscribe("kondisiruang/sensor")
  188.  
  189. try:
  190. while True:
  191. time.sleep(1)
  192.  
  193. except KeyboardInterrupt:
  194. print "exiting"
  195. client.disconnect()
  196. client.loop_stop()
  197. connection.close()
  198. # Setup MQTT end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement