media_player.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import asyncio
  2. import json
  3. import logging
  4. import os.path
  5. import voluptuous as vol
  6. from homeassistant.components.media_player import (
  7. MediaPlayerEntity, PLATFORM_SCHEMA)
  8. from homeassistant.components.media_player.const import (
  9. SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_PREVIOUS_TRACK,
  10. SUPPORT_NEXT_TRACK, SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_MUTE,
  11. SUPPORT_SELECT_SOURCE, MEDIA_TYPE_CHANNEL)
  12. from homeassistant.const import (
  13. CONF_NAME, STATE_OFF, STATE_ON, STATE_UNKNOWN)
  14. import homeassistant.helpers.config_validation as cv
  15. from homeassistant.helpers.restore_state import RestoreEntity
  16. from . import COMPONENT_ABS_DIR, Helper
  17. from .controller import Controller
  18. _LOGGER = logging.getLogger(__name__)
  19. DEFAULT_NAME = "SmartIR Media Player"
  20. DEFAULT_DEVICE_CLASS = "tv"
  21. CONF_UNIQUE_ID = 'unique_id'
  22. CONF_DEVICE_CODE = 'device_code'
  23. CONF_CONTROLLER_DATA = "controller_data"
  24. CONF_POWER_SENSOR = 'power_sensor'
  25. CONF_SOURCE_NAMES = 'source_names'
  26. CONF_DEVICE_CLASS = 'device_class'
  27. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  28. vol.Optional(CONF_UNIQUE_ID): cv.string,
  29. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  30. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  31. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  32. vol.Optional(CONF_POWER_SENSOR): cv.entity_id,
  33. vol.Optional(CONF_SOURCE_NAMES): dict,
  34. vol.Optional(CONF_DEVICE_CLASS, default=DEFAULT_DEVICE_CLASS): cv.string
  35. })
  36. async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
  37. """Set up the IR Media Player platform."""
  38. device_code = config.get(CONF_DEVICE_CODE)
  39. device_files_subdir = os.path.join('codes', 'media_player')
  40. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  41. if not os.path.isdir(device_files_absdir):
  42. os.makedirs(device_files_absdir)
  43. device_json_filename = str(device_code) + '.json'
  44. device_json_path = os.path.join(device_files_absdir, device_json_filename)
  45. if not os.path.exists(device_json_path):
  46. _LOGGER.warning("Couldn't find the device Json file. The component will " \
  47. "try to download it from the GitHub repo.")
  48. try:
  49. codes_source = ("https://raw.githubusercontent.com/"
  50. "smartHomeHub/SmartIR/master/"
  51. "codes/media_player/{}.json")
  52. await Helper.downloader(codes_source.format(device_code), device_json_path)
  53. except Exception:
  54. _LOGGER.error("There was an error while downloading the device Json file. " \
  55. "Please check your internet connection or if the device code " \
  56. "exists on GitHub. If the problem still exists please " \
  57. "place the file manually in the proper directory.")
  58. return
  59. with open(device_json_path) as j:
  60. try:
  61. device_data = json.load(j)
  62. except Exception:
  63. _LOGGER.error("The device JSON file is invalid")
  64. return
  65. async_add_entities([SmartIRMediaPlayer(
  66. hass, config, device_data
  67. )])
  68. class SmartIRMediaPlayer(MediaPlayerEntity, RestoreEntity):
  69. def __init__(self, hass, config, device_data):
  70. self.hass = hass
  71. self._unique_id = config.get(CONF_UNIQUE_ID)
  72. self._name = config.get(CONF_NAME)
  73. self._device_code = config.get(CONF_DEVICE_CODE)
  74. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  75. self._power_sensor = config.get(CONF_POWER_SENSOR)
  76. self._manufacturer = device_data['manufacturer']
  77. self._supported_models = device_data['supportedModels']
  78. self._supported_controller = device_data['supportedController']
  79. self._commands_encoding = device_data['commandsEncoding']
  80. self._commands = device_data['commands']
  81. self._state = STATE_OFF
  82. self._sources_list = []
  83. self._source = None
  84. self._support_flags = 0
  85. self._device_class = config.get(CONF_DEVICE_CLASS)
  86. #Supported features
  87. if 'off' in self._commands and self._commands['off'] is not None:
  88. self._support_flags = self._support_flags | SUPPORT_TURN_OFF
  89. if 'on' in self._commands and self._commands['on'] is not None:
  90. self._support_flags = self._support_flags | SUPPORT_TURN_ON
  91. if 'previousChannel' in self._commands and self._commands['previousChannel'] is not None:
  92. self._support_flags = self._support_flags | SUPPORT_PREVIOUS_TRACK
  93. if 'nextChannel' in self._commands and self._commands['nextChannel'] is not None:
  94. self._support_flags = self._support_flags | SUPPORT_NEXT_TRACK
  95. if ('volumeDown' in self._commands and self._commands['volumeDown'] is not None) \
  96. or ('volumeUp' in self._commands and self._commands['volumeUp'] is not None):
  97. self._support_flags = self._support_flags | SUPPORT_VOLUME_STEP
  98. if 'mute' in self._commands and self._commands['mute'] is not None:
  99. self._support_flags = self._support_flags | SUPPORT_VOLUME_MUTE
  100. if 'sources' in self._commands and self._commands['sources'] is not None:
  101. self._support_flags = self._support_flags | SUPPORT_SELECT_SOURCE
  102. for source, new_name in config.get(CONF_SOURCE_NAMES, {}).items():
  103. if source in self._commands['sources']:
  104. if new_name is not None:
  105. self._commands['sources'][new_name] = self._commands['sources'][source]
  106. del self._commands['sources'][source]
  107. #Sources list
  108. for key in self._commands['sources']:
  109. self._sources_list.append(key)
  110. self._temp_lock = asyncio.Lock()
  111. #Init the IR/RF controller
  112. self._controller = Controller(
  113. self.hass,
  114. self._supported_controller,
  115. self._commands_encoding,
  116. self._controller_data)
  117. async def async_added_to_hass(self):
  118. """Run when entity about to be added."""
  119. await super().async_added_to_hass()
  120. last_state = await self.async_get_last_state()
  121. if last_state is not None:
  122. self._state = last_state.state
  123. @property
  124. def should_poll(self):
  125. """Push an update after each command."""
  126. return True
  127. @property
  128. def unique_id(self):
  129. """Return a unique ID."""
  130. return self._unique_id
  131. @property
  132. def name(self):
  133. """Return the name of the media player."""
  134. return self._name
  135. @property
  136. def device_class(self):
  137. """Return the device_class of the media player."""
  138. return self._device_class
  139. @property
  140. def state(self):
  141. """Return the state of the player."""
  142. return self._state
  143. @property
  144. def media_title(self):
  145. """Return the title of current playing media."""
  146. return None
  147. @property
  148. def media_content_type(self):
  149. """Content type of current playing media."""
  150. return MEDIA_TYPE_CHANNEL
  151. @property
  152. def source_list(self):
  153. return self._sources_list
  154. @property
  155. def source(self):
  156. return self._source
  157. @property
  158. def supported_features(self):
  159. """Flag media player features that are supported."""
  160. return self._support_flags
  161. @property
  162. def device_state_attributes(self) -> dict:
  163. """Platform specific attributes."""
  164. return {
  165. 'device_code': self._device_code,
  166. 'manufacturer': self._manufacturer,
  167. 'supported_models': self._supported_models,
  168. 'supported_controller': self._supported_controller,
  169. 'commands_encoding': self._commands_encoding,
  170. }
  171. async def async_turn_off(self):
  172. """Turn the media player off."""
  173. await self.send_command(self._commands['off'])
  174. if self._power_sensor is None:
  175. self._state = STATE_OFF
  176. self._source = None
  177. await self.async_update_ha_state()
  178. async def async_turn_on(self):
  179. """Turn the media player off."""
  180. await self.send_command(self._commands['on'])
  181. if self._power_sensor is None:
  182. self._state = STATE_ON
  183. await self.async_update_ha_state()
  184. async def async_media_previous_track(self):
  185. """Send previous track command."""
  186. await self.send_command(self._commands['previousChannel'])
  187. await self.async_update_ha_state()
  188. async def async_media_next_track(self):
  189. """Send next track command."""
  190. await self.send_command(self._commands['nextChannel'])
  191. await self.async_update_ha_state()
  192. async def async_volume_down(self):
  193. """Turn volume down for media player."""
  194. await self.send_command(self._commands['volumeDown'])
  195. await self.async_update_ha_state()
  196. async def async_volume_up(self):
  197. """Turn volume up for media player."""
  198. await self.send_command(self._commands['volumeUp'])
  199. await self.async_update_ha_state()
  200. async def async_mute_volume(self, mute):
  201. """Mute the volume."""
  202. await self.send_command(self._commands['mute'])
  203. await self.async_update_ha_state()
  204. async def async_select_source(self, source):
  205. """Select channel from source."""
  206. self._source = source
  207. await self.send_command(self._commands['sources'][source])
  208. await self.async_update_ha_state()
  209. async def send_command(self, command):
  210. async with self._temp_lock:
  211. try:
  212. await self._controller.send(command)
  213. except Exception as e:
  214. _LOGGER.exception(e)
  215. async def async_update(self):
  216. if self._power_sensor is None:
  217. return
  218. power_state = self.hass.states.get(self._power_sensor)
  219. if power_state:
  220. if power_state.state == STATE_OFF:
  221. self._state = STATE_OFF
  222. self._source = None
  223. elif power_state.state == STATE_ON:
  224. self._state = STATE_ON