media_player.py 11 KB

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