wether station gui client
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

smarthome.py 16KB

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