media_player.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. CONF_UNIQUE_ID = 'unique_id'
  22. CONF_DEVICE_CODE = 'device_code'
  23. CONF_CONTROLLER_SEND_SERVICE = "controller_send_service"
  24. CONF_CONTROLLER_COMMAND_TOPIC = "controller_command_topic"
  25. CONF_POWER_SENSOR = 'power_sensor'
  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_SEND_SERVICE): cv.entity_id,
  31. vol.Optional(CONF_CONTROLLER_COMMAND_TOPIC): cv.string,
  32. vol.Optional(CONF_POWER_SENSOR): cv.entity_id
  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 the device code " \
  54. "exists on GitHub. If the problem still exists please " \
  55. "place the file manually in the proper location.")
  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_send_service = config.get(CONF_CONTROLLER_SEND_SERVICE)
  73. self._controller_command_topic = config.get(CONF_CONTROLLER_COMMAND_TOPIC)
  74. self._power_sensor = config.get(CONF_POWER_SENSOR)
  75. self._manufacturer = device_data['manufacturer']
  76. self._supported_models = device_data['supportedModels']
  77. self._supported_controller = device_data['supportedController']
  78. self._commands_encoding = device_data['commandsEncoding']
  79. self._commands = device_data['commands']
  80. self._state = STATE_OFF
  81. self._sources_list = []
  82. self._source = None
  83. self._support_flags = 0
  84. #Supported features
  85. if 'off' in self._commands and self._commands['off'] is not None:
  86. self._support_flags = self._support_flags | SUPPORT_TURN_OFF
  87. if 'on' in self._commands and self._commands['on'] is not None:
  88. self._support_flags = self._support_flags | SUPPORT_TURN_ON
  89. if 'previousChannel' in self._commands and self._commands['previousChannel'] is not None:
  90. self._support_flags = self._support_flags | SUPPORT_PREVIOUS_TRACK
  91. if 'nextChannel' in self._commands and self._commands['nextChannel'] is not None:
  92. self._support_flags = self._support_flags | SUPPORT_NEXT_TRACK
  93. if ('volumeDown' in self._commands and self._commands['volumeDown'] is not None) \
  94. or ('volumeUp' in self._commands and self._commands['volumeUp'] is not None):
  95. self._support_flags = self._support_flags | SUPPORT_VOLUME_STEP
  96. if 'mute' in self._commands and self._commands['mute'] is not None:
  97. self._support_flags = self._support_flags | SUPPORT_VOLUME_MUTE
  98. if 'sources' in self._commands and self._commands['sources'] is not None:
  99. self._support_flags = self._support_flags | SUPPORT_SELECT_SOURCE
  100. #Sources list
  101. for key in self._commands['sources']:
  102. self._sources_list.append(key)
  103. self._temp_lock = asyncio.Lock()
  104. #Init the IR/RF controller
  105. self._controller = Controller(
  106. self.hass,
  107. self._supported_controller,
  108. self._commands_encoding,
  109. self._controller_send_service,
  110. self._controller_command_topic)
  111. async def async_added_to_hass(self):
  112. """Run when entity about to be added."""
  113. await super().async_added_to_hass()
  114. last_state = await self.async_get_last_state()
  115. if last_state is not None:
  116. self._state = last_state.state
  117. @property
  118. def should_poll(self):
  119. """Push an update after each command."""
  120. return True
  121. @property
  122. def unique_id(self):
  123. """Return a unique ID."""
  124. return self._unique_id
  125. @property
  126. def name(self):
  127. """Return the name of the media player."""
  128. return self._name
  129. @property
  130. def state(self):
  131. """Return the state of the player."""
  132. return self._state
  133. @property
  134. def media_title(self):
  135. """Return the title of current playing media."""
  136. return None
  137. @property
  138. def media_content_type(self):
  139. """Content type of current playing media."""
  140. return MEDIA_TYPE_CHANNEL
  141. @property
  142. def source_list(self):
  143. return self._sources_list
  144. @property
  145. def source(self):
  146. return self._source
  147. @property
  148. def supported_features(self):
  149. """Flag media player features that are supported."""
  150. return self._support_flags
  151. @property
  152. def device_state_attributes(self) -> dict:
  153. """Platform specific attributes."""
  154. return {
  155. 'device_code': self._device_code,
  156. 'manufacturer': self._manufacturer,
  157. 'supported_models': self._supported_models,
  158. 'supported_controller': self._supported_controller,
  159. 'commands_encoding': self._commands_encoding,
  160. }
  161. async def async_turn_off(self):
  162. """Turn the media player off."""
  163. await self.send_command(self._commands['off'])
  164. if self._power_sensor is None:
  165. self._state = STATE_OFF
  166. self._source = None
  167. await self.async_update_ha_state()
  168. async def async_turn_on(self):
  169. """Turn the media player off."""
  170. await self.send_command(self._commands['on'])
  171. if self._power_sensor is None:
  172. self._state = STATE_ON
  173. await self.async_update_ha_state()
  174. async def async_media_previous_track(self):
  175. """Send previous track command."""
  176. await self.send_command(self._commands['previousChannel'])
  177. await self.async_update_ha_state()
  178. async def async_media_next_track(self):
  179. """Send next track command."""
  180. await self.send_command(self._commands['nextChannel'])
  181. await self.async_update_ha_state()
  182. async def async_volume_down(self):
  183. """Turn volume down for media player."""
  184. await self.send_command(self._commands['volumeDown'])
  185. await self.async_update_ha_state()
  186. async def async_volume_up(self):
  187. """Turn volume up for media player."""
  188. await self.send_command(self._commands['volumeUp'])
  189. await self.async_update_ha_state()
  190. async def async_mute_volume(self, mute):
  191. """Mute the volume."""
  192. await self.send_command(self._commands['mute'])
  193. await self.async_update_ha_state()
  194. async def async_select_source(self, source):
  195. """Select channel from source."""
  196. self._source = source
  197. await self.send_command(self._commands['sources'][source])
  198. await self.async_update_ha_state()
  199. async def send_command(self, command):
  200. async with self._temp_lock:
  201. try:
  202. await self._controller.send(command)
  203. except Exception as e:
  204. _LOGGER.exception(e)
  205. async def async_update(self):
  206. if self._power_sensor is None:
  207. return
  208. power_state = self.hass.states.get(self._power_sensor)
  209. if power_state:
  210. if power_state.state == STATE_OFF:
  211. self._state = STATE_OFF
  212. self._source = None
  213. elif power_state.state == STATE_ON:
  214. self._state = STATE_ON