media_player.py 9.6 KB

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