wether station gui client
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

smarthome.py 16KB

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