Exemple #1
0
 def sendCmd(self, request):
     #
     command = request.query.command
     #
     try:
         #
         if not self._tokencheck():
             print_error('Nest command could not be sent - error encountered with retrieving new authorisation code', dvc_or_acc_id=self.dvc_or_acc_id())
             return False
         #
         #TODO - possibly update to remove request and set as json payload
         nest_model = request.query.nest_model or False
         nest_device_id = request.query.nest_device_id or False
         nest_device = request.query.nest_device or False
         value = request.query.value or False
         #
         if nest_device == 'thermostats':
             #
             if command == 'temp':
                 #json_cmd = {'devices': {'thermostats': {nest_device_id: {'target_temperature_c': value}}}}
                 json_cmd = {'target_temperature_' + self._temp_unit : float(value)}
                 if self._send_nest_json(json_cmd, nest_model, nest_device, nest_device_id):
                     return self._htmlbody()
             #
         return False
         #
     except Exception as e:
         print_error('Exception encountered sending ' + command + ' - ' + str(e), dvc_or_acc_id=self.dvc_or_acc_id())
         return False
def set_device_detail(type, key, value):
    #
    data = json.load(open(os.path.join('lists', 'list_device_types.json'), 'r'))
    #
    data[type][key] = value
    try:
        #
        with open(os.path.join('lists', 'list_device_types.json'), 'w+') as output_file:
            output_file.write(json.dumps(data, indent=4, separators=(',', ': ')))
            output_file.close()
        #
        return True
    except Exception as e:
        print_error('Could not update "list_device_types.json" with new value - ' + str(e))
        return False
Exemple #3
0
 def _getNewToken(self):
     #
     url = 'https://api.home.nest.com/oauth2/access_token?code={PIN_CODE}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&grant_type=authorization_code'.format(PIN_CODE=self._pincode,
                                                                                                                                                                    CLIENT_ID=self._clientid(),
                                                                                                                                                                    CLIENT_SECRET=self._clientsecret())
     #
     headers = {'Connection': 'close',
                'User-Agent': 'Linux/2.6.18 UDAP/2.0 CentOS/5.8'}
     #
     r = requests.post(url,
                       headers=headers)
     #
     if r.status_code != requests.codes.ok:
         print_error('Auth code not received by Nest server', dvc_or_acc_id=self.dvc_or_acc_id())
         return False
     #
     try:
         response = r.content
     except Exception as e:
         print_error('Auth code not received by Nest server - ' + str(e), dvc_or_acc_id=self.dvc_or_acc_id())
         return False
     #
     if response:
         try:
             data = json.loads(response)
         except Exception as e:
             print_error('Auth code not processed into json object - ' + str(e), dvc_or_acc_id=self.dvc_or_acc_id())
             return False
         #
         exp = datetime.datetime.now() + datetime.timedelta(milliseconds=data['expires_in'])
         #
         set_cfg_account_detail(self._account_id, 'token', data['access_token'])
         set_cfg_account_detail(self._account_id, 'tokenexpiry', exp.strftime(self._dateformat))
         #
         self._token = data['access_token']
         self._tokenexpiry = exp
         #
         print_msg('Success retrieving new Access Token', dvc_or_acc_id=self.dvc_or_acc_id())
         #
         return True
     else:
         return False
Exemple #4
0
 def _htmlbody(self):
     #
     devices_html = '<div class="row">'
     #
     try:
         json_devices = self._read_json_devices()
         #
         if not json_devices:
             print_error('Nest devices could not retrieved from Nest server', dvc_or_acc_id=self.dvc_or_acc_id())
             return False
         #
         # Thermostats
         #
         html_therm = get_device_detail(self._type, 'html_therm')
         #
         if html_therm:
             #
             try:
                 therm_ids = json_devices['thermostats'].keys()
             except:
                 therm_ids = False
             #
             if bool(therm_ids):
                 count = 0
                 for therm in therm_ids:
                     if count> 0 and count % 4 == 0:
                         devices_html += '</div><div class="row">'
                     #
                     colwidth = '3'
                     rem = len(therm_ids) - count
                     if rem == 1:
                         colwidth = '12'
                     elif rem == 2:
                         colwidth = '6'
                     elif rem == 3:
                         colwidth = '4'
                     #
                     nest_device_id = json_devices['thermostats'][therm]['device_id']
                     therm_name = json_devices['thermostats'][therm]['name']
                     #
                     if json_devices['thermostats'][therm]['is_online']:
                         #
                         is_online = 'online'
                         #
                         therm_hvac_state = json_devices['thermostats'][therm]['hvac_state']
                         if therm_hvac_state == 'heating':
                             temp_hvac_statement = 'Heating to'
                         elif therm_hvac_state =='cooling':
                             temp_hvac_statement = 'Cooling to'
                         else:
                             temp_hvac_statement = 'Heat set to'
                         #
                         temp_unit_html = '&#8451;' if self._temp_unit == 'c' else '&#8457'
                         therm_temp_target = json_devices['thermostats'][therm]['target_temperature_{unit}'.format(unit=self._temp_unit)]
                         therm_temp_ambient = json_devices['thermostats'][therm]['ambient_temperature_{unit}'.format(unit=self._temp_unit)]
                         #
                         therm_label = 'Current: '
                         #
                         new_temp_up = therm_temp_target + 0.5
                         new_temp_down = therm_temp_target - 0.5
                         #
                         therm_leaf = json_devices['thermostats'][therm]['has_leaf']
                         #
                     else:
                         #
                         is_online = 'offline'
                         therm_hvac_state = 'offline'
                         temp_hvac_statement = ''
                         temp_unit_html = ''
                         therm_label = 'Offline'
                         therm_temp_target = ''
                         therm_temp_ambient = ''
                         therm_leaf = 'false'
                         new_temp_up = ''
                         new_temp_down = ''
                         #
                     #
                     devices_html += urlopen('web/html_devices/{html_therm}'.format(html_therm=html_therm))\
                         .read().encode('utf-8').format(colwidth=colwidth,
                                                        account_id=str(self._account_id),
                                                        nest_device_id=nest_device_id,
                                                        name=therm_name,
                                                        therm_label=therm_label,
                                                        is_online=is_online,
                                                        temp_hvac=temp_hvac_statement,
                                                        temp_target=therm_temp_target,
                                                        temp_ambient=therm_temp_ambient,
                                                        temp_unit=temp_unit_html,
                                                        has_leaf=str(therm_leaf).lower(),
                                                        hvac=therm_hvac_state,
                                                        new_temp_up=new_temp_up,
                                                        new_temp_down=new_temp_down)
                     #
                     count += 1
                     #
         #
         # Smoke and CO detectors
         #
         html_smoke = get_device_detail(self._type, 'html_smoke')
         #
         if html_smoke:
             #
             try:
                 smoke_ids = json_devices['smoke_co_alarms'].keys()
             except:
                 smoke_ids = False
             #
             if bool(smoke_ids):
                 count = 0
                 for smoke in smoke_ids:
                     if count> 0 and count % 4 == 0:
                         devices_html += '</div><div class="row">'
                     #
                     colwidth = '3'
                     rem = len(smoke_ids) - count
                     if rem == 1:
                         colwidth = '12'
                     elif rem == 2:
                         colwidth = '6'
                     elif rem == 3:
                         colwidth = '4'
                     #
                     nest_device_id = json_devices['smoke_co_alarms'][smoke]['device_id']
                     smoke_name = json_devices['smoke_co_alarms'][smoke]['name']
                     #
                     if json_devices['smoke_co_alarms'][smoke]['is_online']:
                         #
                         smoke_online = 'online'
                         #
                         battery_health = json_devices['smoke_co_alarms'][smoke]['battery_health']
                         # ok / replace
                         #
                         co_alarm_state = json_devices['smoke_co_alarms'][smoke]['co_alarm_state']
                         # ok / warning / emergency
                         #
                         smoke_alarm_state = json_devices['smoke_co_alarms'][smoke]['smoke_alarm_state']
                         # ok / warning / emergency
                         #
                         ui_color_state = json_devices['smoke_co_alarms'][smoke]['ui_color_state']
                         # gray / green / yellow / red
                         #
                     else:
                         #
                         smoke_online = 'offline'
                         battery_health = ''
                         co_alarm_state = ''
                         smoke_alarm_state = ''
                         ui_color_state = ''
                         #
                     #
                     devices_html += urlopen('web/html_devices/{html_smoke}'.format(html_smoke=html_smoke))\
                         .read().encode('utf-8').format(colwidth=colwidth,
                                                        account_id=str(self._account_id),
                                                        nest_device_id=nest_device_id,
                                                        name=smoke_name,
                                                        online=smoke_online,
                                                        ui_color_state=ui_color_state,
                                                        battery_health=battery_health,
                                                        co_alarm_state=co_alarm_state,
                                                        smoke_alarm_state=smoke_alarm_state)
                     #
                     count += 1
                     #
         #
         # Cameras
         #
         html_cam = get_device_detail(self._type, 'html_cam')
         #
         if html_cam:
             #
             try:
                 cam_ids = json_devices['cameras'].keys()
             except:
                 cam_ids = False
             #
             if bool(cam_ids):
                 count = 0
                 for cam in cam_ids:
                     if count> 0 and count % 4 == 0:
                         devices_html += '</div><div class="row">'
                     #
                     colwidth = '3'
                     rem = len(cam_ids) - count
                     if rem == 1:
                         colwidth = '12'
                     elif rem == 2:
                         colwidth = '6'
                     elif rem == 3:
                         colwidth = '4'
                     #
                     nest_device_id = json_devices['cameras'][cam]['device_id']
                     cam_name = json_devices['cameras'][cam]['name']
                     #
                     if json_devices['cameras'][cam]['is_online']:
                         #
                         cam_online = 'Online'
                         img_color = 'blue'
                         #
                         cam_streaming = json_devices['cameras'][cam]['is_streaming']
                         #
                     else:
                         #
                         cam_online = 'Offline'
                         img_color = 'gray'
                         cam_streaming = ''
                         #
                     #
                     devices_html += urlopen('web/html_devices/{html_cam}'.format(html_cam=html_cam))\
                         .read().encode('utf-8').format(colwidth=colwidth,
                                                        account_id=str(self._account_id),
                                                        nest_device_id=nest_device_id,
                                                        name=cam_name,
                                                        color=img_color,
                                                        online=cam_online)
                     #
                     count += 1
                     #
         #
         #
     except Exception as e:
         print_error('Nest devices could not be compiled into html - ' + str(e), dvc_or_acc_id=self.dvc_or_acc_id())
     #
     devices_html += '</div>'
     return devices_html
Exemple #5
0
 def _getHtml_recordings(self):
     #
     try:
         # self.recordings_timestamp = datetime.datetime.now()
         # self.recordings_folders = self._retrieve_recordings('No').replace(' xmlns="http://www.tivo.com/developer/calypso-protocol-1.6/"','')
         # self.recordings_files = self._retrieve_recordings('Yes').replace(' xmlns="http://www.tivo.com/developer/calypso-protocol-1.6/"','')
         #
         series = []
         # Run through items in 'folders' xml and identify group/series names, adding to the series[] variable
         if self.recordings_folders:
             xml_folders = ET.fromstring(self.recordings_folders)
             for item in xml_folders.iter('Item'):
                 details = item.find('Details')
                 # details.find('ContentType').text == 'x-tivo-container/folder'
                 if details.find('Title').text != 'Suggestions' and details.find('Title').text != 'HD Recordings':
                     series.append(details.find('Title').text)
         #
         seriesdrop_html = {}
         series_count = {}
         series_type = {}
         movie_rating = {}
         #
         # Build html group containers for adding file html to later.
         if len(series) > 0:
             for title in series:
                 series_count[title] = 0
                 seriesdrop_html[title] = ''
                 series_type[title] = ''
         #
         # Run through items in 'files' xml and commence building html
         if len(self.recordings_files)>0:
             #
             # Run through individual items
             for item in self.recordings_files:
                 #
                 # If part of a series (check against list created above) then create 'folder' group
                 if item.find('Title').text in series:
                     series_count[item.find('Title').text] += 1
                     # not always an episode title!!
                     try:
                         ep_title = item.find('EpisodeTitle').text
                     except Exception as e:
                         ep_title = '-'
                     #
                     try:
                         imgchan = get_channel_item_image_from_devicekey(self._type, int(item.find('SourceChannel').text))
                         img = '<img style="height: 25px;" src="/img/channel/{imgchan}"/>'.format(imgchan=imgchan)
                     except Exception as e:
                         img = False
                     #
                     try:
                         desc = desc=item.find('Description').text
                     except Exception as e:
                         desc = ''
                     #
                     try:
                         date = int(item.find('CaptureDate').text, 0)
                         date = datetime.datetime.fromtimestamp(date)
                         date = date.strftime('%d-%m-%Y')
                     except Exception as e:
                         date = '-'
                     #
                     try:
                         episodenumber = item.find('EpisodeNumber').text
                         se = episodenumber[:-2]
                         ep = episodenumber[-2:]
                         episodenumber = 'Series {se} Episode {ep}'.format(se=se,ep=ep)
                     except:
                         episodenumber = ''
                     #
                     if item.find('ProgramId').text.startswith('EP'):
                         series_type[item.find('Title').text] = 'tv'
                     elif item.find('ProgramId').text.startswith('MV'):
                         series_type[item.find('Title').text] = 'movie'
                         movie_rating[item.find('Title').text] = item.find('MpaaRating').text
                     else:
                         series_type[item.find('Title').text] = '-'
                     #
                     seriesdrop_html[item.find('Title').text] += '<div class="row">'
                     seriesdrop_html[item.find('Title').text] += '<div class="col-xs-9"><h5>{ep_title}</h5></div>'.format(ep_title=ep_title)
                     seriesdrop_html[item.find('Title').text] += '<div class="col-xs-3" style="text-align: right;">{img}</div>'.format(img=img)
                     seriesdrop_html[item.find('Title').text] += '</div>'
                     seriesdrop_html[item.find('Title').text] += '<div class="row"><div class="col-xs-12"><p>{desc}</p></div></div>'.format(desc=desc)
                     seriesdrop_html[item.find('Title').text] += '<div class="row" style="margin-bottom: 20px">'
                     seriesdrop_html[item.find('Title').text] += '<div class="col-xs-6"><p>{episodenumber}</p></div>'.format(episodenumber=episodenumber)
                     seriesdrop_html[item.find('Title').text] += '<div class="col-xs-6" align="right"><p>{date}</p></div>'.format(date=date)
                     seriesdrop_html[item.find('Title').text] += '</div>'
             #
             # Run through each item in series_html and add to master html_recordings
             html_recordings = '<div class="row">'
             html_recordings += '<div class="col-xs-10"><h5>Title</h5></div>'
             html_recordings += '<div class="col-xs-2" style="text-align: right;"><h5>#</h5></div>'
             html_recordings += '</div>'
             count = 0
             for title in series:
                 html_recordings += '<div class="row btn-col-grey btn_pointer" style="margin-bottom: 5px;" data-toggle="collapse" data-target="#collapse_series{count}">'.format(count=count)
                 #
                 # Based Bootstrap's Scaffolding (12-column grid)
                 # | (9) Title | (2) Number of episodes | (1) Movie/TV Image |
                 # | (9) Episode title | (3) Channel logo |
                 # | (12) Description |
                 # | (6) Series & Episode number | (6) Recording date |
                 #
                 html_recordings += '<div class="col-xs-9"><h5>{title}</h5></div>'.format(title=title)
                 #
                 if series_type[title]=='tv':
                     html_recordings += '<div class="col-xs-2" style="text-align: right;"><h6>{count}</h6></div>'.format(count=series_count[title])
                 # TODO Movie age rating image removed as uses key as opposed to actual age rating in xml
                 # elif series_type[title]=='movie':
                 #     html_recordings += '<div class="col-xs-2" style="text-align: right; padding: 5px;"><img style="height: 25px;" src="/img/movie_rating/BBFC_{rating}.png"/></div>'.format(rating=movie_rating[title])
                 else:
                     html_recordings += '<div class="col-xs-2" style="text-align: right;"></div>'
                 #
                 if series_type[title]=='tv' or series_type[title]=='movie':
                     html_recordings += '<div class="col-xs-1" style="text-align: right; padding: 5px;"><img style="height: 25px;" src="/img/icon/ic_{type}.png"/></div>'.format(type=series_type[title])
                 else:
                     html_recordings += '<div class="col-xs-1" style="text-align: right;"></div>'
                 #
                 html_recordings += '</div>'
                 html_recordings += '<div class="row collapse out" id="collapse_series{count}"><div class="container-fluid">{drop}</div></div>'.format(count=count, drop=seriesdrop_html[title])
                 count += 1
             #
             return html_recordings
         else:
             return '<p>Error</p>'
     except Exception as e:
         print_error('Attempted to create recordings html - {error}'.format(error=e))
         return '<p>Error</p>'