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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 socket_protocol
  15. import task
  16. import tcp_socket
  17. import time
  18. import wetation_protocol
  19. import wx
  20. try:
  21. from config import APP_NAME as ROOT_LOGGER_NAME
  22. except ImportError:
  23. ROOT_LOGGER_NAME = 'root'
  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': socket_protocol.SID_READ_REQUEST,
  58. 'data_id': wetation_protocol.ENVDATA_STATISTIC_DHT,
  59. },
  60. {
  61. 'service_id': socket_protocol.SID_READ_REQUEST,
  62. 'data_id': wetation_protocol.ENVDATA_STATISTIC_BMP,
  63. },
  64. ],
  65. PROT_ID_OUT: [
  66. {
  67. 'service_id': socket_protocol.SID_READ_REQUEST,
  68. 'data_id': wetation_protocol.ENVDATA_STATISTIC_DHT,
  69. },
  70. {
  71. 'service_id': socket_protocol.SID_READ_REQUEST,
  72. 'data_id': wetation_protocol.ENVDATA_STATISTIC_BMP,
  73. },
  74. ],
  75. }
  76. REQUEST_MSGS_FAST = {
  77. PROT_ID_GARAGE: [
  78. {
  79. 'service_id': socket_protocol.SID_READ_REQUEST,
  80. 'data_id': garage_protocol.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. time.sleep(3.5) # Wait for established connections before starting the tasks
  98. self.__task_1s__ = task.periodic(1, self.__task_1s_callback__)
  99. self.__task_10s__ = task.periodic(10, self.__task_10s_callback__)
  100. self.__task_60s__ = task.periodic(60, self.__task_60s_callback__)
  101. def __init_communication__(self):
  102. #
  103. # Start TCP-Clients
  104. for prot_id in self.ALL_PROT_IDS:
  105. cn = self.PROT_NAMES[prot_id]
  106. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  107. logger.info('Initiating communication channel')
  108. c_tcp = tcp_socket.tcp_client_stp(self.PROT_IPS[prot_id], self.PROT_PORTS[prot_id])
  109. self.__prot__[prot_id] = self.PROT_CLASSES[prot_id](c_tcp, secret=self.PROT_SECRETS[prot_id], auto_auth=True, channel_name=cn)
  110. #
  111. self.__prot__[prot_id].register_callback(None, None, self.__prot_resp_callbacks__, prot_id)
  112. def __initiate_data_request__(self, rt, request_msgs):
  113. for prot_id in request_msgs:
  114. cn = self.PROT_NAMES[prot_id]
  115. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  116. for request_msg in request_msgs.get(prot_id, []):
  117. service_id = request_msg['service_id']
  118. data_id = request_msg['data_id']
  119. if self.__prot__[prot_id].connection_established():
  120. logger.debug('Sending data request for service_id %d and data_id %d', service_id, data_id)
  121. self.__prot__[prot_id].send(service_id, data_id, None)
  122. else:
  123. wx.CallAfter(self.__no_data__, prot_id, service_id + 1, data_id)
  124. def __task_1s_callback__(self, rt):
  125. # request data from fast prot ids
  126. self.__initiate_data_request__(rt, self.REQUEST_MSGS_FAST)
  127. # set date and time
  128. wx.CallAfter(self.update_time)
  129. def __task_10s_callback__(self, rt):
  130. # request data from slow prot ids
  131. self.__initiate_data_request__(rt, self.REQUEST_MSGS_SLOW)
  132. def __task_60s_callback__(self, rt):
  133. # reconnect prots if needed
  134. for prot_id in self.ALL_PROT_IDS:
  135. cn = self.PROT_NAMES[prot_id]
  136. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  137. if not self.__prot__[prot_id].connected():
  138. logger.warning("Trying to reconnect prot_id %d", prot_id)
  139. self.__prot__[prot_id].reconnect()
  140. def __validate_response_data__(self, prot_id, service_id, data_id, data):
  141. rv = False
  142. cn = self.PROT_NAMES[prot_id]
  143. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  144. if prot_id == self.PROT_ID_GARAGE:
  145. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == garage_protocol.GATE_POSITION:
  146. rv = isinstance(data, numbers.Number)
  147. elif service_id == socket_protocol.SID_EXECUTE_RESPONSE and data_id == garage_protocol.OPEN_CLOSE_GATE:
  148. if data is True:
  149. rv = True
  150. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  151. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_BMP:
  152. rv = True
  153. for main_key in [bmp_180.KEY_PRESSURE, bmp_180.KEY_TEMPERATURE, bmp_180.KEY_TIME]:
  154. if main_key not in data:
  155. rv = False
  156. break
  157. else:
  158. for sub_key in ['mean', 'min_val', 'max_val', 'quantifier']:
  159. if not isinstance(data[main_key].get(sub_key), numbers.Number):
  160. rv = False
  161. break
  162. elif service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_DHT:
  163. rv = True
  164. for main_key in [dht_22.KEY_HUMIDITY, dht_22.KEY_TEMPERATURE, dht_22.KEY_TIME]:
  165. if main_key not in data:
  166. rv = False
  167. break
  168. else:
  169. for sub_key in ['mean', 'min_val', 'max_val', 'quantifier']:
  170. if not isinstance(data[main_key].get(sub_key), numbers.Number):
  171. rv = False
  172. break
  173. if rv is False:
  174. 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))
  175. return rv
  176. def __prot_resp_callbacks__(self, msg, prot_id):
  177. service_id = msg.get_service_id()
  178. data_id = msg.get_data_id()
  179. data = msg.get_data()
  180. if self.__validate_response_data__(prot_id, service_id, data_id, data):
  181. wx.CallAfter(self.__data__, prot_id, service_id, data_id, data)
  182. return socket_protocol.STATUS_OKAY, None
  183. else:
  184. wx.CallAfter(self.__no_data__, prot_id, service_id, data_id)
  185. return socket_protocol.STATUS_SERVICE_OR_DATA_UNKNOWN, None
  186. def __no_data__(self, prot_id, service_id, data_id):
  187. cn = self.PROT_NAMES[prot_id]
  188. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  189. if prot_id == self.PROT_ID_GARAGE:
  190. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == garage_protocol.GATE_POSITION:
  191. logger.warning('Resetting GUI elements for %s', cn)
  192. self.heading_garage.Show(False)
  193. self.gate_oc.Show(False)
  194. self.gate_open.Show(False)
  195. self.gate_position.Show(False)
  196. self.gate_close.Show(False)
  197. self.Layout()
  198. return
  199. elif service_id == socket_protocol.SID_EXECUTE_RESPONSE and data_id == garage_protocol.OPEN_CLOSE_GATE:
  200. return
  201. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  202. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_BMP:
  203. logger.warning('Resetting GUI elements for %s', cn)
  204. txt_pressure = '- hPa'
  205. if prot_id == self.PROT_ID_IN:
  206. self.in_pressure.SetLabel(txt_pressure)
  207. else:
  208. self.out_pressure.SetLabel(txt_pressure)
  209. self.Layout()
  210. return
  211. elif service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_DHT:
  212. logger.warning('Resetting GUI elements for %s', cn)
  213. txt_temperature = '-.- °C'
  214. txt_humidity = '-.- %'
  215. if prot_id == self.PROT_ID_IN:
  216. self.in_temperature.SetLabel(txt_temperature)
  217. self.in_humidity.SetLabel(txt_humidity)
  218. else:
  219. self.out_temperature.SetLabel(txt_temperature)
  220. self.out_humidity.SetLabel(txt_humidity)
  221. self.Layout()
  222. return
  223. logger.warning("Unknown response with no valid data for prot_id %d, service_id=%d, data_id=%d", prot_id, service_id, data_id)
  224. def __data__(self, prot_id, service_id, data_id, data):
  225. cn = self.PROT_NAMES[prot_id]
  226. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  227. if prot_id == self.PROT_ID_GARAGE:
  228. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == garage_protocol.GATE_POSITION:
  229. logger.debug('Setting %s position to %3d', cn, int(data * 100))
  230. self.heading_garage.Show(True)
  231. self.gate_oc.Show(True)
  232. self.gate_open.Show(True)
  233. self.gate_position.Show(True)
  234. self.gate_close.Show(True)
  235. self.gate_position.SetValue(int(data * 100))
  236. self.Layout()
  237. return
  238. elif service_id == socket_protocol.SID_EXECUTE_RESPONSE and data_id == garage_protocol.OPEN_CLOSE_GATE:
  239. return
  240. elif prot_id in [self.PROT_ID_IN, self.PROT_ID_OUT]:
  241. if service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_BMP:
  242. data = helpers.continues_statistic_multivalue(**data)
  243. logger.debug('Setting %s pressure to %4d hPa', cn, data[bmp_180.KEY_PRESSURE].mean)
  244. #
  245. # Current environmental data
  246. if prot_id == self.PROT_ID_IN:
  247. wx.CallAfter(self.update_current_bmp_env_data, data, self.in_pressure)
  248. else:
  249. wx.CallAfter(self.update_current_bmp_env_data, data, self.out_pressure)
  250. return
  251. elif service_id == socket_protocol.SID_READ_RESPONSE and data_id == wetation_protocol.ENVDATA_STATISTIC_DHT:
  252. data = helpers.continues_statistic_multivalue(**data)
  253. #
  254. # Current environmental data
  255. temp = data[dht_22.KEY_TEMPERATURE].mean
  256. logger.debug('Setting %s temperature to %4.1f °C', cn, temp)
  257. logger.debug('Setting %s humidity to %3.1f %%', cn, data[dht_22.KEY_HUMIDITY].mean)
  258. if prot_id == self.PROT_ID_IN:
  259. if self.__max_temp_in__ is None or temp > self.__max_temp_in__:
  260. self.__max_temp_in__ = temp
  261. if self.__min_temp_in__ is None or temp < self.__min_temp_in__:
  262. self.__min_temp_in__ = temp
  263. 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__)
  264. else:
  265. if self.__max_temp_out__ is None or temp > self.__max_temp_out__:
  266. self.__max_temp_out__ = temp
  267. if self.__min_temp_out__ is None or temp < self.__min_temp_out__:
  268. self.__min_temp_out__ = temp
  269. 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__)
  270. return
  271. logger.warning("Unknown response with valid data for prot_id %d, service_id=%d, data_id=%d", prot_id, service_id, data_id)
  272. def update_current_bmp_env_data(self, env_data, pressure):
  273. pressure.SetLabel('%.0f hPa' % env_data[bmp_180.KEY_PRESSURE].mean)
  274. self.Layout()
  275. def update_current_dht_env_data(self, env_data, temperature, humidity, temperature_min, temperature_max, value_min, value_max):
  276. if isinstance(value_min, numbers.Number) and isinstance(value_max, numbers.Number):
  277. temperature_min.SetLabel('%.1f' % value_min)
  278. temperature_max.SetLabel('%.1f' % value_max)
  279. temperature.SetLabel('%.1f °C' % env_data[dht_22.KEY_TEMPERATURE].mean)
  280. humidity.SetLabel('%.1f %%' % env_data[dht_22.KEY_HUMIDITY].mean)
  281. self.Layout()
  282. def update_time(self):
  283. self.time.SetLabel(time.strftime("%H:%M"))
  284. self.date.SetLabel(time.strftime("%d.%m.%Y"))
  285. self.Layout()
  286. def gate_oc_evt(self, event):
  287. cn = self.PROT_NAMES[self.PROT_ID_GARAGE]
  288. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + cn)
  289. r = wx.MessageDialog(
  290. self,
  291. "Soll das Garagentor betätigt werden?",
  292. "Garage",
  293. wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING
  294. ).ShowModal()
  295. if r == wx.ID_YES:
  296. logger.debug("Gate open/close request")
  297. self.__prot__[self.PROT_ID_GARAGE].send(socket_protocol.SID_EXECUTE_REQUEST, garage_protocol.OPEN_CLOSE_GATE, None)
  298. event.Skip()
  299. def reset_in_temp_minmax_evt(self, event):
  300. self.__min_temp_in__ = None
  301. self.__max_temp_in__ = None
  302. self.in_temperature_min.SetLabel("-.- °C")
  303. self.in_temperature_max.SetLabel("-.- °C")
  304. self.Layout()
  305. event.Skip()
  306. def reset_out_temp_minmax_evt(self, event):
  307. self.__min_temp_out__ = None
  308. self.__max_temp_out__ = None
  309. self.out_temperature_min.SetLabel("-.- °C")
  310. self.out_temperature_max.SetLabel("-.- °C")
  311. self.Layout()
  312. event.Skip()
  313. def run(self):
  314. self.__task_1s__.run()
  315. self.__task_10s__.run()
  316. self.__task_60s__.run()
  317. def close(self):
  318. self.__task_1s__.stop()
  319. self.__task_1s__.join()
  320. self.__task_10s__.stop()
  321. self.__task_10s__.join()
  322. self.__task_60s__.stop()
  323. self.__task_60s__.join()
  324. def __del__(self):
  325. self.close()
  326. class MyApp(wx.App):
  327. def OnInit(self):
  328. self.frame = WetationFrameProt(None, wx.ID_ANY, "")
  329. self.SetTopWindow(self.frame)
  330. self.frame.Show()
  331. return True
  332. if __name__ == "__main__":
  333. report.appLoggingConfigure(os.path.dirname(__file__), config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  334. #
  335. app = MyApp(0)
  336. app.frame.run()
  337. app.MainLoop()
  338. app.frame.close()