media_player.py 9.9 KB

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