media_player.py 11 KB

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