4
0

media_player.py 11 KB

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