Advertisement
Guest User

ECS

a guest
May 5th, 2021
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.83 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import RPi.GPIO as GPIO
  4. from pi_sht1x import SHT1x
  5. from datetime import datetime
  6. import time, mariadb, syslog
  7. from config import Config
  8.  
  9. class Environment:
  10. def __init__(self):
  11. self.log_d('Starting ECS Sensor Daemon...')
  12. self.config = Config()
  13. self.read_config()
  14. self.db_chk()
  15. self.create_tables()
  16. self.temp = None
  17. self.rh = None
  18.  
  19. def db_chk(self):
  20. # Check if db connection is successful for logging purposes
  21. self.log_d('Trying to connect to MariaDB database on ' + self.host + '...')
  22. try:
  23. conn = mariadb.connect(
  24. database = self.database,
  25. user = self.user,
  26. password = self.password,
  27. host = self.host,
  28. port = self.port
  29. )
  30. self.log_d('Connection to MariaDB is succesful!')
  31. except mariadb.Error as e:
  32. self.err_l(e)
  33.  
  34. # log message to daemon log
  35. def log_d(self, log_m):
  36. syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON)
  37. syslog.syslog(log_m)
  38.  
  39. # error logging
  40. def err_l(self, error):
  41. syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_DAEMON)
  42. syslog.syslog(syslog.LOG_ERR, str(error))
  43.  
  44. def read_config(self):
  45. c = self.config.sensor()
  46. self.sense_t = c['sense_t']
  47. self.data_pin = c['data_pin']
  48. self.sck_pin = c['sck_pin']
  49. c = self.config.database()
  50. self.database = c['database']
  51. self.user = c['user']
  52. self.password = c['pass']
  53. self.host = c['host']
  54. self.port= c['port']
  55.  
  56. def create_tables(self):
  57. try:
  58. conn = mariadb.connect(
  59. database = self.database,
  60. user = self.user,
  61. password = self.password,
  62. host = self.host,
  63. port = self.port
  64. )
  65. cur = conn.cursor()
  66.  
  67. # create device table
  68. cur.execute('''CREATE TABLE IF NOT EXISTS device
  69. (dev_id INT PRIMARY KEY,
  70. dev_name VARCHAR(255),
  71. dev_state TINYINT);'''
  72. )
  73. cur.execute('''SELECT * FROM device;''')
  74. row = cur.fetchone()
  75. # initialize device table if empty
  76. if row is None:
  77. cur.execute('''INSERT INTO device VALUES (0, 'Humidifier', 0);''')
  78. cur.execute('''INSERT INTO device VALUES (1, 'Fan', 0);''')
  79.  
  80. # create environment table
  81. cur.execute('''CREATE TABLE IF NOT EXISTS environment
  82. (datetime DATETIME,
  83. humidity DECIMAL(5,2),
  84. temp DECIMAL(5,2));'''
  85. )
  86.  
  87. # create onoff table
  88. cur.execute('''CREATE TABLE IF NOT EXISTS onoff
  89. (datetime DATE,
  90. dev_id INT,
  91. state TINYINT,
  92. humidity DECIMAL(5,2),
  93. temp DECIMAL(5,2),
  94. FOREIGN KEY(dev_id)
  95. REFERENCES device (dev_id));'''
  96. )
  97. conn.close()
  98.  
  99. except mariadb.Error as e:
  100. self.err_l(e)
  101.  
  102. def read(self):
  103. # get env readings
  104. try:
  105. with SHT1x(self.data_pin, self.sck_pin, gpio_mode=GPIO.BCM) as sensor:
  106. temp = sensor.read_temperature()
  107. self.temp = sensor.temperature_fahrenheit
  108. self.rh = sensor.read_humidity(temp)
  109. if (self.temp and self.rh) is not None:
  110. return True
  111. except Exception as e:
  112. self.err_l(e)
  113. return False
  114.  
  115. def write(self):
  116. try:
  117. conn = mariadb.connect(
  118. database = self.database,
  119. user = self.user,
  120. password = self.password,
  121. host = self.host,
  122. port = self.port
  123. )
  124. cur = conn.cursor()
  125. # format time without ms
  126. time_now = datetime.now()
  127. time_now = time_now.strftime('%Y-%m-%d %H:%M:%S')
  128. # get environmental readings
  129. if(self.read()):
  130. cur.execute("INSERT INTO environment VALUES (?, ?, ?)", (time_now, self.rh, self.temp))
  131. self.rh = None
  132. self.temp = None
  133. conn.commit()
  134. conn.close()
  135.  
  136. except mariadb.Error as e:
  137. self.err_l(e)
  138.  
  139. def main():
  140. env = Environment()
  141. while True:
  142. # re-read config to allow configuration changes without restarting daemon
  143. env.read_config()
  144. env.write()
  145. time.sleep(env.sense_t)
  146.  
  147. if __name__ == '__main__':
  148. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement