wether station gui client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

smarthome.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. import config
  5. from rpi_envsens.dht import dht_22
  6. from rpi_envsens.bmp import bmp_180
  7. import helpers
  8. import garage_protocol
  9. import gui
  10. import logging
  11. import numbers
  12. import os
  13. import report
  14. import task
  15. import tcp_socket
  16. import time
  17. import wetation_protocol
  18. import wx
  19. try:
  20. from config import APP_NAME as ROOT_LOGGER_NAME
  21. except ImportError:
  22. ROOT_LOGGER_NAME = 'root'
  23. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  24. class WetationFrameProt(gui.Wetation):
  25. PROT_ID_GARAGE = 0
  26. PROT_ID_IN = 1
  27. PROT_ID_OUT = 2
  28. ALL_PROT_IDS = [PROT_ID_GARAGE, PROT_ID_IN, PROT_ID_OUT, ]
  29. PROT_NAMES = {
  30. PROT_ID_GARAGE: u'garage',
  31. PROT_ID_IN: u'wet-in',
  32. PROT_ID_OUT: u'wet-out',
  33. }
  34. PROT_IPS = {
  35. PROT_ID_GARAGE: config.server_garage_ip,
  36. PROT_ID_IN: config.server_in_ip,
  37. PROT_ID_OUT: config.server_out_ip,
  38. }
  39. PROT_PORTS = {
  40. PROT_ID_GARAGE: config.server_garage_port,
  41. PROT_ID_IN: config.server_in_port,
  42. PROT_ID_OUT: config.server_out_port,
  43. }
  44. PROT_SECRETS = {
  45. PROT_ID_GARAGE: config.server_garage_secret,
  46. PROT_ID_IN: config.server_in_secret,
  47. PROT_ID_OUT: config.server_out_secret,
  48. }
  49. PROT_CLASSES = {
  50. PROT_ID_GARAGE: garage_protocol.my_base_protocol_tcp,
  51. PROT_ID_IN: wetation_protocol.my_base_protocol_tcp,
  52. PROT_ID_OUT: wetation_protocol.my_base_protocol_tcp,
  53. }
  54. REQUEST_MSGS_SLOW = {
  55. PROT_ID_IN: [
  56. {
  57. 'service_id': wetation_protocol.my_base_protocol_tcp.SID_READ_REQUEST,
  58. 'data_id': wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_DHT,
  59. },
  60. {
  61. 'service_id': wetation_protocol.my_base_protocol_tcp.SID_READ_REQUEST,
  62. 'data_id': wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_BMP,
  63. },
  64. ],
  65. PROT_ID_OUT: [
  66. {
  67. 'service_id': wetation_protocol.my_base_protocol_tcp.SID_READ_REQUEST,
  68. 'data_id': wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_DHT,
  69. },
  70. {
  71. 'service_id': wetation_protocol.my_base_protocol_tcp.SID_READ_REQUEST,
  72. 'data_id': wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_BMP,
  73. },
  74. ],
  75. }
  76. REQUEST_MSGS_FAST = {
  77. PROT_ID_GARAGE: [
  78. {
  79. 'service_id': garage_protocol.my_base_protocol_tcp.SID_READ_REQUEST,
  80. 'data_id': garage_protocol.my_base_protocol_tcp.GATE_POSITION,
  81. },
  82. ],
  83. }
  84. def __init__(self, *args, **kwds):
  85. self.__min_temp_in__ = None
  86. self.__min_temp_out__ = None
  87. self.__max_temp_in__ = None
  88. self.__max_temp_out__ = None
  89. self.__prot__ = {}
  90. gui.Wetation.__init__(self, *args, **kwds)
  91. self.in_temperature_min.Bind(wx.EVT_LEFT_DOWN, self.reset_in_temp_minmax_evt)
  92. self.in_temperature_max.Bind(wx.EVT_LEFT_DOWN, self.reset_in_temp_minmax_evt)
  93. self.out_temperature_min.Bind(wx.EVT_LEFT_DOWN, self.reset_out_temp_minmax_evt)
  94. self.out_temperature_max.Bind(wx.EVT_LEFT_DOWN, self.reset_out_temp_minmax_evt)
  95. self.ShowFullScreen(config.FULL_SCREEN)
  96. self.__init_communication__()
  97. self.__task_1s__ = task.periodic(1, self.__task_1s_callback__)
  98. self.__task_10s__ = task.periodic(10, self.__task_10s_callback__)
  99. self.__task_60s__ = task.periodic(60, self.__task_60s_callback__)
  100. def __init_communication__(self):
  101. #
  102. # Start TCP-Clients
  103. for prot_id in self.ALL_PROT_IDS:
  104. logger.debug('Initiating communication channel for prot_id %d', prot_id)
  105. c_tcp = tcp_socket.tcp_client_stp(self.PROT_IPS[prot_id], self.PROT_PORTS[prot_id], rx_log_lvl=logging.DEBUG)
  106. self.__prot__[prot_id] = self.PROT_CLASSES[prot_id](c_tcp, secret=self.PROT_SECRETS[prot_id], auto_auth=True, channel_name=self.PROT_NAMES[prot_id])
  107. #
  108. self.__prot__[prot_id].register_callback(None, None, self.__prot_resp_callbacks__, prot_id)
  109. def __initiate_data_request__(self, rt, request_msgs):
  110. for prot_id in request_msgs:
  111. for request_msg in request_msgs.get(prot_id, []):
  112. service_id = request_msg['service_id']
  113. data_id = request_msg['data_id']
  114. if self.__prot__[prot_id].connection_established():
  115. logger.debug('Sending data request for prot_id %d, service_id %d and data_id %d', prot_id, service_id, data_id)
  116. self.__prot__[prot_id].send(service_id, data_id, None)
  117. else:
  118. wx.CallAfter(self.__no_data__, prot_id, service_id + 1, data_id)
  119. def __task_1s_callback__(self, rt):
  120. # request data from fast prot ids
  121. self.__initiate_data_request__(rt, self.REQUEST_MSGS_FAST)
  122. # set date and time
  123. wx.CallAfter(self.update_time)
  124. def __task_10s_callback__(self, rt):
  125. # request data from slow prot ids
  126. self.__initiate_data_request__(rt, self.REQUEST_MSGS_SLOW)
  127. def __task_60s_callback__(self, rt):
  128. # reconnect prots if needed
  129. for prot_id in self.ALL_PROT_IDS:
  130. if not self.__prot__[prot_id].connected():
  131. logger.debug("Trying to reconnect prot_id %d", prot_id)
  132. self.__prot__[prot_id].reconnect()
  133. def __validate_response_data__(self, prot_id, service_id, data_id, data):
  134. rv = False
  135. if prot_id == self.PROT_ID_GARAGE:
  136. if service_id == garage_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.GATE_POSITION:
  137. rv = isinstance(data, numbers.Number)
  138. elif service_id == garage_protocol.my_base_protocol_tcp.SID_EXECUTE_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.OPEN_CLOSE_GATE:
  139. if data is True:
  140. rv = True
  141. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  142. if service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_BMP:
  143. rv = True
  144. for main_key in [bmp_180.KEY_PRESSURE, bmp_180.KEY_TEMPERATURE, bmp_180.KEY_TIME]:
  145. if main_key not in data:
  146. rv = False
  147. break
  148. else:
  149. for sub_key in ['mean', 'min_val', 'max_val', 'quantifier']:
  150. if not isinstance(data[main_key].get(sub_key), numbers.Number):
  151. rv = False
  152. break
  153. elif service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_DHT:
  154. rv = True
  155. for main_key in [dht_22.KEY_HUMIDITY, dht_22.KEY_TEMPERATURE, dht_22.KEY_TIME]:
  156. if main_key not in data:
  157. rv = False
  158. break
  159. else:
  160. for sub_key in ['mean', 'min_val', 'max_val', 'quantifier']:
  161. if not isinstance(data[main_key].get(sub_key), numbers.Number):
  162. rv = False
  163. break
  164. if rv is False:
  165. logger.warning("Validation failed for message: prot_id=%s, service_id=%s, data_id=%s, data=%s", repr(prot_id), repr(service_id), repr(data_id), repr(data))
  166. return rv
  167. def __prot_resp_callbacks__(self, msg, prot_id):
  168. service_id = msg.get_service_id()
  169. data_id = msg.get_data_id()
  170. data = msg.get_data()
  171. if self.__validate_response_data__(prot_id, service_id, data_id, data):
  172. wx.CallAfter(self.__data__, prot_id, service_id, data_id, data)
  173. return wetation_protocol.my_base_protocol_tcp.STATUS_OKAY, None
  174. else:
  175. wx.CallAfter(self.__no_data__, prot_id, service_id, data_id)
  176. return wetation_protocol.my_base_protocol_tcp.STATUS_SERVICE_OR_DATA_UNKNOWN, None
  177. def __no_data__(self, prot_id, service_id, data_id):
  178. if prot_id == self.PROT_ID_GARAGE:
  179. if service_id == garage_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.GATE_POSITION:
  180. logger.debug('Resetting GUI for prot_id %d, service_id=%d, data_id=%d', prot_id, service_id, data_id)
  181. self.heading_garage.Show(False)
  182. self.gate_oc.Show(False)
  183. self.gate_open.Show(False)
  184. self.gate_position.Show(False)
  185. self.gate_close.Show(False)
  186. self.Layout()
  187. return
  188. elif service_id == garage_protocol.my_base_protocol_tcp.SID_EXECUTE_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.OPEN_CLOSE_GATE:
  189. return
  190. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  191. if service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_BMP:
  192. logger.debug('Resetting GUI for prot_id %d, service_id=%d, data_id=%d', prot_id, service_id, data_id)
  193. txt_pressure = '- hPa'
  194. if prot_id == self.PROT_ID_IN:
  195. self.in_pressure.SetLabel(txt_pressure)
  196. else:
  197. self.out_pressure.SetLabel(txt_pressure)
  198. self.Layout()
  199. return
  200. elif service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_DHT:
  201. logger.debug('Resetting GUI for prot_id %d, service_id=%d, data_id=%d', prot_id, service_id, data_id)
  202. txt_temperature = '-.- °C'
  203. txt_humidity = '-.- %'
  204. if prot_id == self.PROT_ID_IN:
  205. self.in_temperature.SetLabel(txt_temperature)
  206. self.in_humidity.SetLabel(txt_humidity)
  207. else:
  208. self.out_temperature.SetLabel(txt_temperature)
  209. self.out_humidity.SetLabel(txt_humidity)
  210. self.Layout()
  211. return
  212. logger.warning("Unknown response with no valid data for prot_id %d, service_id=%d, data_id=%d", prot_id, service_id, data_id)
  213. def __data__(self, prot_id, service_id, data_id, data):
  214. if prot_id == self.PROT_ID_GARAGE:
  215. if service_id == garage_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.GATE_POSITION:
  216. self.heading_garage.Show(True)
  217. self.gate_oc.Show(True)
  218. self.gate_open.Show(True)
  219. self.gate_position.Show(True)
  220. self.gate_close.Show(True)
  221. self.gate_position.SetValue(int(data * 100))
  222. self.Layout()
  223. return
  224. elif service_id == garage_protocol.my_base_protocol_tcp.SID_EXECUTE_RESPONSE and data_id == garage_protocol.my_base_protocol_tcp.OPEN_CLOSE_GATE:
  225. return
  226. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  227. if service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_BMP:
  228. data = helpers.continues_statistic_multivalue(**data)
  229. #
  230. # Current environmental data
  231. if prot_id == self.PROT_ID_IN:
  232. wx.CallAfter(self.update_current_bmp_env_data, data, self.in_pressure)
  233. else:
  234. wx.CallAfter(self.update_current_bmp_env_data, data, self.out_pressure)
  235. return
  236. elif service_id == wetation_protocol.my_base_protocol_tcp.SID_READ_RESPONSE and data_id == wetation_protocol.my_base_protocol_tcp.ENVDATA_STATISTIC_DHT:
  237. data = helpers.continues_statistic_multivalue(**data)
  238. #
  239. # Current environmental data
  240. temp = data[dht_22.KEY_TEMPERATURE].mean
  241. if prot_id == self.PROT_ID_IN:
  242. if self.__max_temp_in__ is None or temp > self.__max_temp_in__:
  243. self.__max_temp_in__ = temp
  244. if self.__min_temp_in__ is None or temp < self.__min_temp_in__:
  245. self.__min_temp_in__ = temp
  246. wx.CallAfter(self.update_current_dht_env_data, data, self.in_temperature, self.in_humidity, self.in_temperature_min, self.in_temperature_max, self.__min_temp_in__, self.__max_temp_in__)
  247. else:
  248. if self.__max_temp_out__ is None or temp > self.__max_temp_out__:
  249. self.__max_temp_out__ = temp
  250. if self.__min_temp_out__ is None or temp < self.__min_temp_out__:
  251. self.__min_temp_out__ = temp
  252. wx.CallAfter(self.update_current_dht_env_data, data, self.out_temperature, self.out_humidity, self.out_temperature_min, self.out_temperature_max, self.__min_temp_out__, self.__max_temp_out__)
  253. return
  254. logger.warning("Unknown response with valid data for prot_id %d, service_id=%d, data_id=%d", prot_id, service_id, data_id)
  255. def update_current_bmp_env_data(self, env_data, pressure):
  256. pressure.SetLabel('%.0f hPa' % env_data[bmp_180.KEY_PRESSURE].mean)
  257. self.Layout()
  258. def update_current_dht_env_data(self, env_data, temperature, humidity, temperature_min, temperature_max, value_min, value_max):
  259. if isinstance(value_min, numbers.Number) and isinstance(value_max, numbers.Number):
  260. temperature_min.SetLabel('%.1f' % value_min)
  261. temperature_max.SetLabel('%.1f' % value_max)
  262. temperature.SetLabel('%.1f °C' % env_data[dht_22.KEY_TEMPERATURE].mean)
  263. humidity.SetLabel('%.1f %%' % env_data[dht_22.KEY_HUMIDITY].mean)
  264. self.Layout()
  265. def update_time(self):
  266. self.time.SetLabel(time.strftime("%H:%M"))
  267. self.date.SetLabel(time.strftime("%d.%m.%Y"))
  268. self.Layout()
  269. def gate_oc_evt(self, event):
  270. r = wx.MessageDialog(
  271. self,
  272. "Soll das Garagentor betätigt werden?",
  273. "Garage",
  274. wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING
  275. ).ShowModal()
  276. if r == wx.ID_YES:
  277. logger.debug("Gate open/close request")
  278. self.__prot__[self.PROT_ID_GARAGE].send(garage_protocol.my_base_protocol_tcp.SID_EXECUTE_REQUEST, garage_protocol.my_base_protocol_tcp.OPEN_CLOSE_GATE, None)
  279. event.Skip()
  280. def reset_in_temp_minmax_evt(self, event):
  281. self.__min_temp_in__ = None
  282. self.__max_temp_in__ = None
  283. self.in_temperature_min.SetLabel("-.- °C")
  284. self.in_temperature_max.SetLabel("-.- °C")
  285. self.Layout()
  286. event.Skip()
  287. def reset_out_temp_minmax_evt(self, event):
  288. self.__min_temp_out__ = None
  289. self.__max_temp_out__ = None
  290. self.out_temperature_min.SetLabel("-.- °C")
  291. self.out_temperature_max.SetLabel("-.- °C")
  292. self.Layout()
  293. event.Skip()
  294. def run(self):
  295. self.__task_1s__.run()
  296. self.__task_10s__.run()
  297. self.__task_60s__.run()
  298. def close(self):
  299. self.__task_1s__.stop()
  300. self.__task_1s__.join()
  301. self.__task_10s__.stop()
  302. self.__task_10s__.join()
  303. self.__task_60s__.stop()
  304. self.__task_60s__.join()
  305. def __del__(self):
  306. self.close()
  307. class MyApp(wx.App):
  308. def OnInit(self):
  309. self.frame = WetationFrameProt(None, wx.ID_ANY, "")
  310. self.SetTopWindow(self.frame)
  311. self.frame.Show()
  312. return True
  313. if __name__ == "__main__":
  314. report.appLoggingConfigure(os.path.dirname(__file__), config.LOGTARGET, ((config.APP_NAME, 'DEBUG'), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  315. #
  316. app = MyApp(0)
  317. app.frame.run()
  318. app.MainLoop()
  319. app.frame.close()