Best Python code snippet using testcontainers-python_python
gui.py
Source:gui.py
1import ipaddress2import logging3import logging.config4import os5from time import sleep6import PySimpleGUI as sg7import phue8import hue_light9from edhue import EDHue, initialize, save_config10from log import configure_logger11ELITE_ORANGE = '#f07b05'12def GUI_main():13 def GUI_start(ip, light):14 logger.info('In GUImain - start')15 logger.info('Validating bridge connection.')16 connected = False17 try:18 sg.popup_quick_message('Trying to connect', text_color=ELITE_ORANGE,19 font=('euro caps', 32))20 ed_hue = EDHue(ip, light)21 connected = True22 except phue.PhueRequestTimeout:23 logger.error('Unable to talk to the bridge on ip: ' + str(ip))24 sg.PopupError('Unable to talk to the Philips Hue bridge at '25 + str(ip)26 + '. Please verify the IP address or use the scan '27 'for bridge option in Configure.',28 title='Connection error')29 return connected30 logger.info('ED Hue is active. Awaiting events...')31 running = True32 ed_hue.light_on()33 return connected, running34 def GUI_cleanup(ip, light='', connected=False):35 logger.debug('In cleanup')36 if connected:37 if light != '':38 try:39 ed_hue = EDHue(ip, light)40 ed_hue.light_off()41 ed_hue.stop()42 except ConnectionRefusedError:43 logger.error('Unable to connect to bridge.')44 except phue.PhueRegistrationException:45 logger.error('Hue Bridge registration error.')46 logger.info('This bridge has not yet been registered.')47 except phue.PhueRequestTimeout:48 logger.error('Unable to talk to bridge on ip: ' + str(ip))49 logger.info('See you in the Black, Commander!')50 logger.info('o7')51 def GUI_configure_ui(bridge_IP='0.0.0.0', bridge_light=''):52 logger.debug('In Configure UI')53 logger.debug('Passed in values (if any):')54 logger.debug(' Hue IP: ' + bridge_IP)55 logger.debug(' Hue Light: ' + bridge_light)56 '''57 Philips Hue Bridge configuration58 '''59 # Define the window's contents60 layout = [[sg.Text('Philips Hue Bridge Configuration')],61 [sg.Text("Type in your Philips Hue Bridge IP address, or "62 "press 'Scan for Bridge'\nto discover via mDNS.")],63 [sg.Text()],64 [sg.Text('Hue Bridge IP:'),65 sg.Input(default_text=bridge_IP, key='-HUE_BRIDGE-',66 enable_events=True)],67 [sg.Text()],68 [sg.Button('Ok', bind_return_key=True),69 sg.Button('Scan for Bridge', key='scan'),70 sg.Button('Cancel')]]71 # Create the window72 window = sg.Window('Configure Hue Bridge', layout)73 # Display and interact with the Window using an Event Loop74 while True:75 event, values = window.read()76 # See if user wants to quit or window was closed77 if event == sg.WINDOW_CLOSED or event == 'Cancel':78 logger.debug('Cancel selected, or window closed.')79 if event != sg.WINDOW_CLOSED:80 window.close()81 return bridge_IP, bridge_light82 if event == 'scan':83 logger.debug('Scan selected.')84 ip, host, name, mdns_type = hue_light.get_bridge()85 window['-HUE_BRIDGE-'].update(ip)86 if event == 'Ok':87 try:88 ip = values['-HUE_BRIDGE-']89 ipaddress.ip_address(ip)90 logger.debug('Valid IP address given: ' + ip)91 bridge_IP = ip92 except ValueError:93 logger.debug('Invalid IP address entered. '94 'Showing error window.')95 sg.PopupError('Please enter a valid IP address')96 try:97 sg.popup_quick_message('Trying to connect',98 text_color=ELITE_ORANGE,99 font=('euro caps', 32))100 ed_hue = EDHue(bridge_IP)101 window.close()102 break103 except phue.PhueRequestTimeout:104 logger.error('Unable to talk to the bridge on ip: '105 + str(bridge_IP))106 sg.PopupError('Unable to talk to the Philips Hue bridge at '107 + str(bridge_IP)108 + '. Please verify the IP address or use '109 'the scan for bridge option.',110 title='Connection error')111 except phue.PhueRegistrationException:112 sg.PopupError('This Philips Hue bridge is not yet '113 'registered. Please push the button on the '114 'bridge and press OK on the previous window '115 'within 30 seconds.')116 # if last character in input element is invalid, remove it117 if event == '-HUE_BRIDGE-' \118 and values['-HUE_BRIDGE-'] \119 and values['-HUE_BRIDGE-'][-1] not in '0123456789.:':120 window['-HUE_BRIDGE-'].update(values['-HUE_BRIDGE-'][:-1])121 '''122 Philips Hue Light(s) configuration123 '''124 lights = hue_light.get_lights(bridge_IP)125 light_list = []126 widest = 0127 logger.debug('Determining how wide to make the window.')128 for light in lights:129 light_list.append(light[1])130 width = len(light[1])131 if width > widest:132 widest = width133 logger.debug('Widest element is ' + str(widest) + ' chars long.')134 layout = [[sg.Text('Philips Hue Bridge Configuration')],135 [sg.Text("Please select a light, and press either OK to "136 "accept or 'Flash Light' to\nturn the light on "137 "and off.")],138 [sg.Text()],139 [sg.Text('Hue Bridge IP:'),140 sg.Input(default_text=bridge_IP, key='-HUE_BRIDGE-',141 disabled_readonly_background_color='#000000',142 disabled=True)],143 [sg.Text('Hue Light(s): '),144 sg.Listbox(values=light_list, default_values=bridge_light,145 size=((widest + 1), 10), key='-HUE_LIGHT-')],146 [sg.Text()],147 [sg.Button('Ok', bind_return_key=True),148 sg.Button('Flash Light', key='Flash'),149 sg.Button('Cancel')]]150 # Create the window151 window = sg.Window('Configure Hue Light', layout)152 # Display and interact with the Window using an Event Loop153 while True:154 event, values = window.read()155 # See if user wants to quit or window was closed156 if event == sg.WINDOW_CLOSED or event == 'Cancel':157 logger.debug('Cancel selected, or window closed.')158 break159 if event == 'Ok':160 bridge_light = values['-HUE_LIGHT-'][0]161 logger.debug('Light selected: ' + bridge_light)162 break163 if event == 'Flash':164 bridge_light = values['-HUE_LIGHT-'][0]165 logger.debug('Flashing light')166 logger.debug(' IP: ' + str(bridge_IP))167 logger.debug(' Light: ' + str(bridge_light))168 ed_hue.set_light(bridge_light)169 if ed_hue.get_status():170 logger.debug('Light is on, sending off command.')171 ed_hue.light_off()172 sleep(1)173 ed_hue.light_on()174 else:175 logger.debug('Light is off, sending on command.')176 ed_hue.light_on()177 sleep(1)178 ed_hue.light_off()179 # Finish up by removing from the screen180 logger.debug('Closing Configure window and returning:')181 logger.debug(' Hue IP: ' + bridge_IP)182 logger.debug(' Hue Light: ' + bridge_light)183 logger.debug('Saving selected configuration for the future.')184 save_config(bridge=bridge_IP, light=bridge_light)185 window.close()186 logger.debug('Returning to main menu.')187 return bridge_IP, bridge_light188 '''189 GUI MAIN190 '''191 bridge_IP, bridge_light, debug = initialize()192 logging.config.dictConfig(configure_logger())193 # create logger with 'EDHue'194 logger = logging.getLogger('EDHue.GUI')195 logger.info('Starting.')196 connected = False197 running_status = False198 ed_hue_status = 'Stopped'199 ed_hue_status_color = 'Red'200 # Define my theme201 sg.LOOK_AND_FEEL_TABLE['EliteTheme'] = {'BACKGROUND': '#000000', # Black202 'TEXT': '#ffffff', # White203 'INPUT': ELITE_ORANGE,204 'TEXT_INPUT': '#ffffff', # White205 'SCROLL': ELITE_ORANGE,206 'BUTTON': ('white', ELITE_ORANGE),207 'PROGRESS': ('white', 'black'),208 'BORDER': 1,209 'SLIDER_DEPTH': 0,210 'PROGRESS_DEPTH': 0,211 }212 # Switch to use your newly created theme213 sg.theme('EliteTheme')214 # Call a popup to show what the theme looks like215 # sg.popup_get_text('This how the MyNewTheme custom theme looks')216 # Define the window's contents217 layout = [[sg.Button(key='StartImage',218 image_filename=os.path.join('assets', 'edlogo2.gif'),219 pad=(0, 0)),220 sg.Button(button_text='Elite Dangerous Hue Light Sync',221 key='StartText', font=('euro caps', 38), pad=(0, 0))],222 [sg.Text('Configured Bridge:', justification='right',223 size=(18, 0)),224 sg.Text(bridge_IP, key='Bridge', justification='left',225 size=(18, 0))],226 [sg.Text('Configured Light:', justification='right',227 size=(18, 0)),228 sg.Text(bridge_light, key='Light', justification='left',229 size=(18, 0))],230 [sg.Text('Status:', justification='right',231 size=(18, 0)),232 sg.Text(ed_hue_status, key='Light', justification='left',233 text_color=ed_hue_status_color, size=(18, 0))],234 [sg.Text()],235 [sg.Button('Configure', font=('euro caps', 32),236 pad=((0, 6), (0, 0))),237 sg.Button('Exit', size=(4, 1), pad=((545, 0), (0, 0)),238 font=('euro caps', 32))]239 ]240 # Create the window241 window = sg.Window('E:D Hue Light Sync', layout, margins=(25, 25),242 background_color='#000000', element_justification='c')243 # Display and interact with the Window using an Event Loop244 while True:245 event, values = window.read()246 # See if user wants to quit or window was closed247 if event == sg.WINDOW_CLOSED or event == 'Exit':248 break249 if event == 'StartImage' or event == 'StartText':250 if bridge_IP == '' and bridge_light == '':251 sg.popup_error('Both the Philips Hue Bridge and Light source '252 'must be populated.\n'253 'Click on configure to set them up.')254 elif bridge_IP == '':255 sg.popup_error('The Philips Hue Bridge must be populated.\n'256 'Click on configure to set it up.')257 elif bridge_light == '':258 sg.popup_error('The Philips Hue Light source must be '259 'populated.\n'260 'Click on configure to set it up.')261 connected, running_status = GUI_start(bridge_IP, bridge_light)262 if event == 'Configure':263 window.hide()264 bridge_IP, bridge_light = GUI_configure_ui(bridge_IP, bridge_light)265 window.un_hide()266 window.force_focus()267 logger.debug('Returned bridge IP: ' + bridge_IP)268 logger.debug('Returned Light: ' + bridge_light)269 window['Bridge'].update(bridge_IP)270 window['Light'].update(bridge_light)271 if running_status:272 ed_hue_status = 'Running'273 ed_hue_status_color = 'Green'274 # Define the window's contents275 layout = [[sg.Button(key='StartImage',276 image_filename=os.path.join('assets', 'edlogo2.gif'),277 pad=(0, 0)),278 sg.Button(button_text='Elite Dangerous Hue Light Sync',279 key='StartText', font=('euro caps', 38), pad=(0, 0))],280 [sg.Text('Configured Bridge:', justification='right',281 size=(18, 0)),282 sg.Text(bridge_IP, key='Bridge', justification='left',283 size=(18, 0))],284 [sg.Text('Configured Light:', justification='right',285 size=(18, 0)),286 sg.Text(bridge_light, key='Light', justification='left',287 size=(18, 0))],288 [sg.Text('Status:', justification='right',289 size=(18, 0)),290 sg.Text(ed_hue_status, key='Light', justification='left',291 text_color=ed_hue_status_color, size=(18, 0))],292 [sg.Text()],293 [sg.Button('Configure', font=('euro caps', 32),294 pad=((0, 6), (0, 0))),295 sg.Button('Exit', size=(4, 1), pad=((545, 0), (0, 0)),296 font=('euro caps', 32))]297 ]298 # rereate the window299 window.close()300 window = sg.Window('E:D Hue Light Sync', layout, margins=(25, 25),301 background_color='#000000',302 element_justification='c')303 # Finish up by removing from the screen and doing some cleanup304 window.close()305 if connected:306 non_blocking = True307 else:308 non_blocking = False309 sg.popup_auto_close('See you in the Black, Commander.\n\no7',310 background_color='#000000', text_color=ELITE_ORANGE,311 no_titlebar=True, button_type=5, font=('euro caps', 32),312 non_blocking=non_blocking, auto_close_duration=5)313 GUI_cleanup(ip=bridge_IP, light=bridge_light, connected=connected)314if __name__ == '__main__':...
hue_setup.py
Source:hue_setup.py
...8class HueSetup:9 """ Get or create infos to connect to Philips Hue """10 bridge_url = None11 def __init__(self):12 bridge_ip = self._get_bridge_ip()13 username = self._get_cached_username(bridge_ip)14 print "Cached username: " + str(username)15 if username is None or not self._is_connected(bridge_ip, username):16 username = self._connect_user(bridge_ip)17 self.bridge_url = self._create_url(bridge_ip, username)18 self._set_cache(bridge_ip, username)19 def _get_bridge_ip(self):20 response = requests.get('http://www.meethue.com/api/nupnp').json()21 bridge_ip = response[0]["internalipaddress"] if type(response) is list else response["internalipaddress"]22 return bridge_ip23 def _is_connected(self, bridge_ip, username):24 is_connected = False25 resource = {'which':'system'}26 response = requests.get(self._create_url(bridge_ip, username)).json()27 if 'lights' in response:28 print 'Connected to the Hub'29 is_connected = True30 elif 'error' in response[0]:31 error = response[0]['error']32 if error['type'] == 1:33 is_connected = False...
setup.py
Source:setup.py
1# encoding: utf-82from __future__ import unicode_literals3import json4from os import system5from packages import requests6from packages.workflow import Workflow3 as Workflow7import request8import utils9def set_bridge(bridge_ip=None):10 try:11 if not bridge_ip:12 bridge_ip = utils.search_for_bridge()13 if not bridge_ip:14 print('No bridges found on your network. Try specifying the IP address.'.encode('utf-8'))15 return None16 workflow = Workflow()17 # Create API user for the workflow18 r = requests.post(19 'http://{bridge_ip}/api'.format(bridge_ip=bridge_ip),20 data=json.dumps({'devicetype': 'Alfred 2'}),21 timeout=322 )23 resp = r.json()[0]24 if resp.get('error'):25 print('Setup Error: %s' % resp['error'].get('description').encode('utf-8'))26 else:27 workflow.settings['bridge_ip'] = bridge_ip28 workflow.settings['username'] = resp['success']['username']29 print('Success! You can now control your lights by using the "hue" keyword.'.encode('utf-8'))30 except requests.exceptions.RequestException:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!