def find_hues(): hue_ssdp_list = ssdp.discover("urn:schemas-upnp-org:device:basic:1", timeout=1, max_wait=1, interface="eth4") for hue_ssdp in hue_ssdp_list: description_xml = requests.get(hue_ssdp.location) root = ET.XML(description_xml.text) base_url = root.find("hue:URLBase", namespaces=XMLNS).text yield base_url
def new_controller_form(request, api='philips'): discovered = ssdp.discover('Philips Hue') ip_addresses = [ ssdp.parse_ip_address(discovery.location) for discovery in discovered ] context = {'api': api, 'ip_addresses': ip_addresses, 'error': 0} return render(request, 'MachineInterface/add_controller.html', context)
def discover_and_connect_bridge(): ssdp_responses = ssdp.discover("device") registered = False help_printed = False for response in ssdp_responses: hub_ip = verify_hue_upnp(response.location) if hub_ip: print("Found hub at: %s" % hub_ip) discover_start = time.time() while not(registered and (time.time() - discover_start > 90)): # Time out in 90 seconds try: bridge = phue.Bridge(hub_ip) registered = True print("Conected to hub at: %s" % hub_ip) return bridge except phue.PhueRegistrationException: registered = False time.sleep(1) if not help_printed: print( "Please press the button on the Hue bridge to connect this app.") help_printed = True print ("Hub discovery timed out.")
def discover_and_connect_bridge(): ssdp_responses = ssdp.discover("device") registered = False help_printed = False for response in ssdp_responses: hub_ip = verify_hue_upnp(response.location) if hub_ip: print("Found hub at: %s" % hub_ip) discover_start = time.time() while not(registered and (time.time() - discover_start > 90)): # Time out in 90 seconds try: bridge = phue.Bridge(hub_ip) registered = True print("Conected to hub at: %s" % hub_ip) return bridge except phue.PhueRegistrationException: registered = False time.sleep(1) if not help_printed: print( "Please press the button on the Hue bridge to connect this app.") help_printed = True print ("Hub discovery timed out.")
def start(ssdp, id): while worker_info[id]['task'].running == True: services = ssdp.discover("urn:schemas-upnp-org:service:api:1.1") if len(services) > 0: for srv in services: nb.nb_add_rack(srv) time.sleep(5)
def doSSDPDiscovery(): searchTarget = "urn:hyperion-project.org:device:basic:1" filteredResponse = [] ipPortUsnList = [] selectedServer = -1 # start sync search response = ssdp.discover(searchTarget) for item in response: if item.st == searchTarget: filteredResponse.append(item) if len(filteredResponse) > 0: ipPortUsnList = getSSDPData(filteredResponse) # if there is more than one entry the user should select one if len(filteredResponse) > 1: selectedServer = xbmcgui.Dialog().select(getLS(32102), buildSelectList(ipPortUsnList)) else: xbmcgui.Dialog().ok('Hyperion Control', getLS(32103), '-> '+ipPortUsnList[0]["ip"]+':'+str(ipPortUsnList[0]["port"])) selectedServer = 0 #check user input and push settings if valid if selectedServer > -1: setSetting('SSDPUSN', ipPortUsnList[selectedServer]["usn"]) setSetting('ip', ipPortUsnList[selectedServer]["ip"]) setSetting('port', ipPortUsnList[selectedServer]["port"]) # TODO SSDP USN checks on usual startup to sync ip and port if required. Requires async ssdp else: xbmcgui.Dialog().ok('Hyperion Control', getLS(32104)) return
def find_hues(): hue_ssdp_list = ssdp.discover('urn:schemas-upnp-org:device:basic:1', timeout=1, max_wait=1) for hue_ssdp in hue_ssdp_list: description_xml = requests.get(hue_ssdp.location) root = ET.XML(description_xml.text) base_url = root.find('hue:URLBase', namespaces=XMLNS).text yield base_url
def setup(self): print("Setting up..") if self.ip == "": r = ssdp.discover("upnp:rootdevice") self.ip = next( urlparse(x.location).netloc[:-3] for x in r if "IpBridge" in x.server) self.getLights() self.getGroups()
def main(): print('Finding Devices....') # Discover Roku Devices all_devices = ssdp.discover('roku:ecp') # Get the device info for each roku # Display the user named device as a list to chose from # Accept user input for device commands selected_device = select_device(all_devices) wait_for_command(selected_device)
def _discover_hue(self): responses = ssdp.discover('ssdp:discover') urn_device = 'urn:schemas-upnp-org:device:basic:1' targets = filter(lambda x: x.st == urn_device, responses) devices = [] for target in targets: resp = requests.get(target.location) dev = DeviceInfo(resp.content) if dev.model_name.startswith('Philips hue bridge'): devices.append(dev) return devices
def discoverTVip(): tvdevices = [] tvdevicesIPs = [] tvdevicesNames = [] discoverCount = 0 while True: discoverCount += 1 #dicovered = ssdp.discover('urn:samsung.com:service:MultiScreenService:1') #dicovered = ssdp.discover('ssdp:all') #dicovered = ssdp.discover('urn:samsung.com:device:RemoteControlReceiver:1') dicovered = ssdp.discover(ssdpModeMap[settings.ssdpmode]) if xbmc.abortRequested: break if len(dicovered) > 0: break if discoverCount > 2: break for tvdevice in dicovered: tvXMLloc = tvdevice.location xbmc.log('tvXMLloc: ' + str(tvXMLloc), xbmc.LOGDEBUG) tvip = getIPfromString(tvXMLloc) if tvip: xbmc.log('tvip: ' + str(tvip), xbmc.LOGDEBUG) tvFriendlyName = settings.getLocalizedString(30503) #Unknown try: tvXML = urllib2.urlopen(tvXMLloc).read() xbmc.log('tvXML: ' + str(tvXML), xbmc.LOGDEBUG) tvXMLdom = parseString(tvXML) tvFriendlyName = tvXMLdom.getElementsByTagName('friendlyName')[0].childNodes[0].toxml() except urllib2.HTTPError as e: if e.code == 401: # If Remote Access has been denied - we cannot even read the description tvFriendlyName = settings.getLocalizedString(30501) #Access Denied. Check Permissions else: toNotify(settings.getLocalizedString(30502) + ' ' + str(e)) xbmc.log('HTTP Error ' + str(e), xbmc.LOGERROR) except: xbmc.log('Exception getting friendly name', xbmc.LOGERROR) if tvip not in tvdevicesIPs: tvdevicesIPs.append(tvip) tvdevicesNames.append(tvFriendlyName + ' @ ' + tvip) tvdevices.append([tvip, tvFriendlyName]) xbmc.log('Discovered devices count: ' + str(len(tvdevices)), xbmc.LOGINFO) if len(tvdevices) > 1: myselect = dialog.select(settings.getLocalizedString(30514), tvdevicesNames) #Select your TV device toNotify(settings.getLocalizedString(30504) + ': ' + str(tvdevices[myselect][1])) #Discovered TV return tvdevices[myselect] elif len(tvdevices) == 1: toNotify(settings.getLocalizedString(30504) + ': ' + str(tvdevices[0][1])) #Discovered TV return tvdevices[0] else: toNotify(settings.getLocalizedString(30505)) #Samsung TV is not detected return []
def _discover_hue(self): responses = ssdp.discover('ssdp:discover') urn_device = 'urn:schemas-upnp-org:device:basic:1' targets = filter(lambda x: x.st == urn_device, responses) devices = [] for target in targets: resp = requests.get(target.location) dev = DeviceInfo(resp.content) if dev.model_name.startswith('Philips hue bridge'): devices.append(dev) return devices
def find_wifi_shield(self, shield_name=None, wifi_shield_cb=None): """Detects Ganglion board MAC address if more than 1, will select first. Needs root.""" if self.log: print("Try to find WiFi shields on your local wireless network") print("Scanning for %d seconds nearby devices..." % self.timeout) list_ip = [] list_id = [] found_shield = False def wifi_shield_found(response): res = requests.get(response.location, verify=False).text device_description = xmltodict.parse(res) try : cur_shield_name = str( device_description['root']['device']['serialNumber']) cur_base_url = str(device_description['root']['URLBase']) cur_ip_address = re.findall(r'[0-9]+(?:\.[0-9]+){3}', cur_base_url)[0] except : # it's probably a direct connection # TODO [] : check for a 404 response... cur_shield_name = 'DIRECT SHIELD' cur_ip_address = '192.168.4.1' list_id.append(cur_shield_name) list_ip.append(cur_ip_address) found_shield = True if shield_name is None: print("Found WiFi Shield %s with IP Address %s" % (cur_shield_name, cur_ip_address)) if wifi_shield_cb is not None: wifi_shield_cb(cur_ip_address) else: if shield_name == cur_shield_name: if wifi_shield_cb is not None: wifi_shield_cb(cur_ip_address) ssdp_hits = ssdp.discover("urn:schemas-upnp-org:device:Basic:1", timeout=self.timeout, wifi_found_cb=wifi_shield_found) nb_wifi_shields = len(list_id) if nb_wifi_shields < 1: print("No WiFi Shields found ;(") raise OSError('Cannot find OpenBCI WiFi Shield with local name') if nb_wifi_shields > 1: print( "Found " + str(nb_wifi_shields) + ", selecting first named: " + list_id[0] + " with IPV4: " + list_ip[0]) return list_ip[0]
def findstb(): # Use SSDP to discover the set top box. stbip = '' services = ssdp.discover("urn:schemas-nds-com:service:SkyRemote:1") if (services): for service in (x for x in services if x.st == "urn:schemas-nds-com:service:SkyRemote:1"): stbip = service.location.split('//')[1].split(':')[0] if (DEBUG): print("Found a Set Top Box at: " + stbip) return stbip
def connect(): device = ssdp.discover('urn:schemas-sony-com:service:ScalarWebAPI:1') address = None if len(device) > 0: for x, y in device.items(): address = x config = requests.get(address) root = ET.fromstring(config.text) #api endpoint path in xml endpoint = root[1][8][1][0][1].text return endpoint else: raise RuntimeError('No device found')
def findBridgeIP(): devicesOnNetwork = ssdp.discover("IpBridge") for device in devicesOnNetwork: print device url = device.location response = requests.get(url) if 'Philips' in response.text: root = ET.fromstring(response.text) for child in root: if 'URLBase' in child.tag: bridgeHost = urlparse(child.text).hostname print "Bridge IP" print bridgeHost return bridgeHost
def find_wifi_shield(self, shield_name=None, wifi_shield_cb=None): """Detects Ganglion board MAC address -- if more than 1 around, will select first. Needs root privilege.""" if self.log: print("Try to find WiFi shields on your local wireless network") print("Scanning for 5 seconds nearby devices...") list_ip = [] list_id = [] found_shield = False def wifi_shield_found(response): res = urllib2.urlopen(response.location).ser_read() device_description = xmltodict.parse(res) cur_shield_name = str( device_description['root']['device']['serialNumber']) cur_base_url = str(device_description['root']['URLBase']) cur_ip_address = re.findall(r'[0-9]+(?:\.[0-9]+){3}', cur_base_url)[0] list_id.append(cur_shield_name) list_ip.append(cur_ip_address) found_shield = True if shield_name is None: print("Found WiFi Shield %s with IP Address %s" % (cur_shield_name, cur_ip_address)) if wifi_shield_cb is not None: wifi_shield_cb(cur_ip_address) else: if shield_name == cur_shield_name: if wifi_shield_cb is not None: wifi_shield_cb(cur_ip_address) ssdp_hits = ssdp.discover("urn:schemas-upnp-org:device:Basic:1", timeout=3, wifi_found_cb=wifi_shield_found) nb_wifi_shields = len(list_id) if nb_wifi_shields < 1: print("No WiFi Shields found ;(") raise OSError('Cannot find OpenBCI WiFi Shield with local name') if nb_wifi_shields > 1: print("Found " + str(nb_wifi_shields) + ", selecting first named: " + list_id[0] + " with IPV4: " + list_ip[0]) return list_ip[0]
def discover_devices(self): discover = ssdp.discover('urn:schemas-upnp-org:service:ContentDirectory:1') print("found", len(discover), "devices") for d in discover: print("Trying", d.location) req = requests.get(d.location) tree = remove_ns(req.content) device_node = tree.findall('device') if 'Panasonic' not in device_node[0].find('manufacturer').text: print('Skipping non DMR device') continue else: print('Found DMR @ ', d.location) device_info = {'USN': d.usn, 'location': d.location, 'XML': req.content, 'last_updated': datetime.now()} self.dlna_database.update_devices(device_info) return device_info
def find_camera(): '''Send an SSDP request to get the camera URL''' import ssdp SSDP_ST = "urn:schemas-sony-com:service:ScalarWebAPI:1" ret = ssdp.discover(SSDP_ST, if_ip=opts.iface) if len(ret) == 0: return None dms_location = ret[0].location print("Fetching DMS from %s" % dms_location) req = requests.request('GET', dms_location) tree = ET.ElementTree(file=StringIO.StringIO(req.content)) for elem in tree.iter(): if elem.tag == '{urn:schemas-sony-com:av}X_ScalarWebAPI_ActionList_URL': print("Found camera at %s" % elem.text) return elem.text return None
def __sFindCameraURL(self, sInterface): sSSDPString = "urn:schemas-sony-com:service:ScalarWebAPI:1" sInterfaceIP = self.__sFindInterfaceIPAddress(sInterface) print("Interface IP Address: %s" % sInterfaceIP) sRet = ssdp.discover(sSSDPString, if_ip=sInterfaceIP) if len(sRet) == 0: return None sDMS_URL = sRet[0].location print("Fetching DMS from %s" % sDMS_URL) xmlReq = requests.request('GET', sDMS_URL) xmlTree = ET.ElementTree(file=StringIO.StringIO(xmlReq.content)) for xmlElem in xmlTree.iter(): if xmlElem.tag == '{urn:schemas-sony-com:av}X_ScalarWebAPI_ActionList_URL': print("Found camera at %s" % xmlElem.text) return xmlElem.text return None
def find_camera(): '''Send an SSDP request to get the camera URL''' import ssdp SSDP_ST = "urn:schemas-sony-com:service:ScalarWebAPI:1"; ret = ssdp.discover(SSDP_ST, if_ip=opts.iface) if len(ret) == 0: return None dms_location = ret[0].location print("Fetching DMS from %s" % dms_location) req = requests.request('GET', dms_location) tree = ET.ElementTree(file=StringIO.StringIO(req.content)) for elem in tree.iter(): if elem.tag == '{urn:schemas-sony-com:av}X_ScalarWebAPI_ActionList_URL': print("Found camera at %s" % elem.text) return elem.text return None
def __sFindCameraURL(self, sInterface): sSSDPString = "urn:schemas-sony-com:service:ScalarWebAPI:1"; sInterfaceIP = self.__sFindInterfaceIPAddress(sInterface) print ("Interface IP Address: %s" % sInterfaceIP) sRet = ssdp.discover(sSSDPString, if_ip=sInterfaceIP) if len(sRet) == 0: return None sDMS_URL = sRet[0].location print("Fetching DMS from %s" % sDMS_URL) xmlReq = requests.request('GET', sDMS_URL) xmlTree = ET.ElementTree(file=StringIO.StringIO(xmlReq.content)) for xmlElem in xmlTree.iter(): if xmlElem.tag == '{urn:schemas-sony-com:av}X_ScalarWebAPI_ActionList_URL': print("Found camera at %s" % xmlElem.text) return xmlElem.text return None
def discover(source_ip=None): """ Discover a Sony device on the network, parse its capabilities file and return a mapping of service/URLs :param source_ip: the address of the local interface to discover from :return: dict """ logger.info('Discovering device on network') res = ssdp.discover(SSDP_SERVICE, source_ip=source_ip) if not res: logger.error('No device found in network (source_ip=%s)', source_ip) raise IOError('No device found in network') device = res[0] logger.info('Found device %s', device) logger.info('Requesting its description xml file (%s)', device.location) r = requests.get(device.location) logger.info('File obtained, parsing XML') services = parse_capabilities_xml(r.text) return services
def search(): """Look for Hue bridges and print their IPs.""" print("Looking for Hue bridges...") devices = ssdp.discover("ssdp:all") if len(devices): print("Found %s possible devices, one moment..." % len(devices)) bridges = [] for d in devices: desc = requests.get(d.location) if "Philips hue bridge" in desc.text: bridges.append(d.location) if len(bridges): print("\nBridges found:") for i in range(0, len(bridges)): url = urlparse(bridges[i]) address = url.netloc if ":" in address: address = address[:address.index(":")] print("%s\t%s" % (i + 1, address))
def scan(self): done = False while (not done): #scans the network for all roku tvs tvs = (ssdp.discover("roku:ecp")) counter = 0 #empty dict intialized to dump to JSON later tvDict = {} #prints out all TVs found for tv in tvs: #regex to only have the IP adress of the TV tvIPaddr = re.search(r"[/]\d{3}.\d{3}.\d.\d*", str(tvs[counter])) tvIPaddr = tvIPaddr.group().strip("/") #GET request that receives lots of information but im only interested in the device name. deviceInfo = requests.get("http://" + tvIPaddr + ":8060/query/device-info") #regex to single out the device name line deviceName = re.search(r"[u][s][e][r].*>\w*", str(deviceInfo.text)) deviceName = deviceName.group() #find the index that is essentially the end of the device name endIndex = deviceName.find("<") deviceName = deviceName[17:endIndex] #writes the name & ip addr to the dict tvDict[deviceName] = tvIPaddr counter += 1 #dumps to json file with open( r'C:\Users\Chip\Documents\personalProjects\personalProjects\rokuController\tvNameAndIP.txt', 'w') as json_file: json.dump(tvDict, json_file, indent=2) done = True
def discoverThermostats(timeout=5, logger=_LOGGER): """Discover thermostats on the network supporting the Venstar ColorTouch API Parameters: timeout -- timeout for SSDP broadcast (defaults to 5) logger -- logger to use for errors """ thermostats = [] # discover devices via the SSDP M-SEARCH method responses = ssdp.discover(_SSDP_SEARCH_TARGET, timeout=timeout) logger.debug("SSDP discovery returned %i thermostats.", len(responses)) # iterate through the responses for response in responses: logger.debug("Thermostat found in discover - USN: %s, Location: %s", response.usn, response.location) # parse out the id, name, type, and hostname from the response usn = response.usn tID = usn[usn.find("ecp:") + 4:usn.find(":name")].replace(":", "") tName = unquote(usn[usn.find("name:") + 5:usn.find(":type")]) tType = usn[usn.find("type:") + 5:] tHostName = urlparse(response.location).netloc thermostatInfo = { "id": tID, "name": tName, "type": tType, "hostname": tHostName } # append to thermostat list thermostats.append(thermostatInfo) return thermostats
# import gphoto2cffi as gp import requests import json import ssdp from bs4 import BeautifulSoup import xml.etree.ElementTree as ET response = ssdp.discover() for item in response.split('\n'): if 'LOCATION' in item: location_url = item.strip().split(' ')[ 1] #get location url fron ssdp response device_xml_request = requests.get(location_url) xml_file = str(device_xml_request.content.decode()) xml = ET.fromstring(xml_file) device_tag = xml.find('{urn:schemas-upnp-org:device-1-0}device') api_info = device_tag.find( '{urn:schemas-sony-com:av}X_ScalarWebAPI_DeviceInfo') api_version = api_info.find( '{urn:schemas-sony-com:av}X_ScalarWebAPI_Version').text service_list = api_info.find( '{urn:schemas-sony-com:av}X_ScalarWebAPI_ServiceList') print(api_version) api_service_urls = {} for service in service_list: service_type = service.find( '{urn:schemas-sony-com:av}X_ScalarWebAPI_ServiceType').text action_url = service.find( '{urn:schemas-sony-com:av}X_ScalarWebAPI_ActionList_URL').text api_service_urls[service_type] = action_url
def findtv(self, id=None): result_list = [] r = [] sr = 0 # Find htpc.managers ip ip = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip.connect(('8.8.8.8', 80)) local_ip = ip.getsockname()[0] iid = 0 # Tries to find the mac, this is likly to be the wrong one.. my tv accepts anything #mac = ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2)) # Fake the mac since my tv accepts anything mac = 'E8:E0:B7:D3:A4:62' # Since udp sucks balls while True: sr += 1 search = ssdp.discover('ssdp:all') #search = ssdp.discover('urn:samsung.com:device:RemoteControlReceiver:1') r.append(search) if len(r) >= 2: break for i in r: for item in i: host = self.getIPfromString(item.location) if host: try: desc = urllib2.urlopen(item.location).read() d = {} xml = xmltodict.parse(desc) if 'tv' in xml["root"]["device"]["friendlyName"].lower(): iid += 1 d["name"] = xml["root"]["device"]["friendlyName"] d["host"] = host d["id"] = iid d["tv_model"] = xml["root"]["device"]["modelName"] d["local_ip"] = local_ip d["mac"] = mac result_list.append(d) except Exception as e: pass# if id: for tt in result_list: if tt["id"] == int(id): return tt if len(result_list) == 1: return result_list # Remove dupe dicts from list getvals = operator.itemgetter('host') result_list.sort(key=getvals) result = [] for k, g in itertools.groupby(result_list, getvals): result.append(g.next()) result_list[:] = result return result_list
import lumix_control import ssdp discover = ssdp.discover('urn:schemas-upnp-org:service:ContentDirectory:1') IP = "" if len(discover): for response in discover: location = response.location IP = location.split(':60606')[0].replace('http://', '') # Have only tested this on my camera if IP != "": control = lumix_control.CameraControl(IP)
def getRokus(): return ssdp.discover("roku:ecp")[0].location
def getServers(): # Find uPNP servers try: timeoutval = float(settings('ssdp_timeout')) contenturl = '' msgdialogprogress = xbmcgui.DialogProgress() dialogmsg = translate(30402) dialoghead = translate(30401) msgdialogprogress.create(dialoghead, dialogmsg) servers = ssdp.discover("urn:schemas-upnp-org:device:MediaServer:1", timeout=timeoutval) srvcount = len(servers) addtlmsg = ' ' + str(srvcount) + ' uPNP servers discovered.' ddialogmsg = dialogmsg + addtlmsg msgdialogprogress.update(50, ddialogmsg) xbmc.sleep(1000) if srvcount > 0: msynclog = 'Mezzmo sync server search: ' + str( srvcount) + ' uPNP servers found.' xbmc.log(msynclog, xbmc.LOGNOTICE) mezlogUpdate(msynclog) else: msynclog = translate(30403) xbmcgui.Dialog().notification(translate(30401), msynclog, addon_icon, 5000) xbmc.log(msynclog, xbmc.LOGNOTICE) mezlogUpdate(msynclog) return 0 onlyShowMezzmo = False a = 0 mcount = 0 # Count of Mezzmo serves found for server in servers: url = server.location try: response = urllib2.urlopen(url) xmlstring = re.sub(' xmlns="[^"]+"', '', response.read(), count=1) e = xml.etree.ElementTree.fromstring(xmlstring) device = e.find('device') friendlyname = device.find('friendlyName').text manufacturer = device.find('manufacturer').text if manufacturer != None: manufacturer = manufacturer.text else: manufacturer = 'None' modelnumber = device.find('modelNumber') if modelnumber != None: modelnumber = modelnumber.text else: modelnumber = 'None' udn = device.find('UDN') if udn != None: udn = udn.text else: udn = 'None' description = device.find('modelDescription') if description != None: description = description.text else: description = 'None' serviceList = device.find('serviceList') iconList = device.find('iconList') iconurl = '' isMezzmo = False if manufacturer != None and manufacturer == 'Conceiva Pty. Ltd.': iconurl = addon_icon isMezzmo = True mcount += 1 elif iconList != None: bestWidth = 0 for icon in iconList.findall('icon'): mimetype = icon.find('mimetype').text width = icon.find('width').text height = icon.find('height').text width = int(width) if width > bestWidth: bestWidth = width iconurl = icon.find('url').text if iconurl.startswith('/'): end = url.find('/', 8) length = len(url) iconurl = url[:end - length] + iconurl else: end = url.rfind('/') length = len(url) iconurl = url[:end - length] + '/' + iconurl else: iconurl = addon_path + '/resources/media/otherserver.png' if isMezzmo or onlyShowMezzmo == False: contenturl = '' for service in serviceList.findall('service'): serviceId = service.find('serviceId') if serviceId.text == 'urn:upnp-org:serviceId:ContentDirectory': contenturl = service.find('controlURL').text if contenturl.startswith('/'): end = url.find('/', 8) length = len(url) contenturl = url[:end - length] + contenturl elif 'http' not in contenturl: end = url.rfind('/') length = len(url) contenturl = url[:end - length] + '/' + contenturl updateServers(url, friendlyname, contenturl, manufacturer, modelnumber, \ iconurl, description, udn) except urllib2.URLError, urllib2.HTTPError: # Detect Server Issues msynclog = 'Mezzmo uPNP server not responding: ' + url xbmc.log(msynclog, xbmc.LOGNOTICE) mezlogUpdate(msynclog) dialog_text = translate(30405) + url xbmcgui.Dialog().ok(translate(30404), dialog_text) pass a += 1 percent = int(a / float(srvcount) * 50) + 50 dialogmsg = str(a) + ' / ' + str(srvcount) + ' server completed.' msgdialogprogress.update(percent, dialogmsg) xbmc.sleep(500) msgdialogprogress.close() return mcount
def listServers(force): timeoutval = float(addon.getSetting('ssdp_timeout')) saved_servers = addon.getSetting('saved_servers') if len(saved_servers) == 0 or force: servers = ssdp.discover("urn:schemas-upnp-org:device:MediaServer:1", timeout=timeoutval) # save the servers for faster loading addon.setSetting('saved_servers', pickle.dumps(servers)) else: servers = pickle.loads(saved_servers) onlyShowMezzmo = addon.getSetting('only_mezzmo_servers') == 'true' itemurl = build_url({'mode': 'serverList', 'refresh': True}) li = xbmcgui.ListItem('Refresh', iconImage=addon.getAddonInfo("path") + '/resources/media/refresh.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=itemurl, listitem=li, isFolder=True) xbmc.log('Mezzmo server search: ' + str(len(servers)), xbmc.LOGNOTICE) for server in servers: url = server.location xbmc.log('Mezzmo server url: ' + url, xbmc.LOGNOTICE) try: response = urllib2.urlopen(url) xmlstring = re.sub(' xmlns="[^"]+"', '', response.read(), count=1) e = xml.etree.ElementTree.fromstring(xmlstring) device = e.find('device') friendlyname = device.find('friendlyName').text manufacturer = device.find('manufacturer').text serviceList = device.find('serviceList') iconList = device.find('iconList') iconurl = '' isMezzmo = False if manufacturer != None and manufacturer == 'Conceiva Pty. Ltd.': iconurl = addon.getAddonInfo("path") + '/icon.png' isMezzmo = True elif iconList != None: bestWidth = 0 for icon in iconList.findall('icon'): mimetype = icon.find('mimetype').text width = icon.find('width').text height = icon.find('height').text if width > bestWidth: bestWidth = width iconurl = icon.find('url').text if iconurl.startswith('/'): end = url.find('/', 8) length = len(url) iconurl = url[:end - length] + iconurl else: end = url.rfind('/') length = len(url) iconurl = url[:end - length] + '/' + iconurl else: iconurl = addon.getAddonInfo( "path") + '/resources/media/otherserver.png' if isMezzmo or onlyShowMezzmo == False: contenturl = '' for service in serviceList.findall('service'): serviceId = service.find('serviceId') if serviceId.text == 'urn:upnp-org:serviceId:ContentDirectory': contenturl = service.find('controlURL').text if contenturl.startswith('/'): end = url.find('/', 8) length = len(url) contenturl = url[:end - length] + contenturl else: end = url.rfind('/') length = len(url) contenturl = url[:end - length] + '/' + contenturl itemurl = build_url({ 'mode': 'server', 'contentdirectory': contenturl }) li = xbmcgui.ListItem(friendlyname, iconImage=iconurl) li.setArt({ 'thumb': iconurl, 'poster': iconurl, 'fanart': addon.getAddonInfo("path") + 'fanart.jpg' }) xbmcplugin.addDirectoryItem(handle=addon_handle, url=itemurl, listitem=li, isFolder=True) except Exception as e: printexception() pass setViewMode('servers') xbmcplugin.endOfDirectory(addon_handle, updateListing=force)
#!/usr/bin/python # -*- coding: UTF-8 -*- from random import randint import ssdp import yeelight from time import sleep yeelight_master = ssdp.discover(":yeelink:yeebox") yeeIP = yeelight_master[0].location print 'IP of gateway: ',yeeIP yee = yeelight.yeelight(yeeIP) yee.start() try: for i in range(0,1000): #yee.changeColor('0001',randint(0,255),randint(0,255),randint(0,255)) #yee.control('0001',randint(0,255),randint(0,255),randint(0,255),randint(0,255)) sleep(1) print '>>> ',yee.readBuf() finally: yee.close()
def listServers(force): timeoutval = float(addon.getSetting('ssdp_timeout')) saved_servers = addon.getSetting('saved_servers') if len(saved_servers) == 0 or force: servers = ssdp.discover("urn:schemas-upnp-org:device:MediaServer:1", timeout=timeoutval) # save the servers for faster loading addon.setSetting('saved_servers', pickle.dumps(servers)) else: servers = pickle.loads(saved_servers) onlyShowMezzmo = addon.getSetting('only_mezzmo_servers') == 'true' itemurl = build_url({'mode': 'serverList', 'refresh': True}) li = xbmcgui.ListItem('Refresh', iconImage=addon.getAddonInfo("path") + '/resources/media/refresh.png') xbmcplugin.addDirectoryItem(handle=addon_handle, url=itemurl, listitem=li, isFolder=True) xbmc.log('Mezzmo server search: ' + str(len(servers)), xbmc.LOGNOTICE) for server in servers: url = server.location xbmc.log('Mezzmo server url: ' + url, xbmc.LOGNOTICE) try: response = urllib2.urlopen(url) xmlstring = re.sub(' xmlns="[^"]+"', '', response.read(), count=1) e = xml.etree.ElementTree.fromstring(xmlstring) device = e.find('device') friendlyname = device.find('friendlyName').text manufacturer = device.find('manufacturer').text serviceList = device.find('serviceList') iconList = device.find('iconList') iconurl = '' isMezzmo = False if manufacturer != None and manufacturer == 'Conceiva Pty. Ltd.': iconurl = addon.getAddonInfo("path") + '/icon.png' isMezzmo = True elif iconList != None: bestWidth = 0 for icon in iconList.findall('icon'): mimetype = icon.find('mimetype').text width = icon.find('width').text height = icon.find('height').text if width > bestWidth: bestWidth = width iconurl = icon.find('url').text if iconurl.startswith('/'): end = url.find('/', 8) length = len(url) iconurl = url[:end-length] + iconurl else: end = url.rfind('/') length = len(url) iconurl = url[:end-length] + '/' + iconurl else: iconurl = addon.getAddonInfo("path") + '/resources/media/otherserver.png' if isMezzmo or onlyShowMezzmo == False: contenturl = '' for service in serviceList.findall('service'): serviceId = service.find('serviceId') if serviceId.text == 'urn:upnp-org:serviceId:ContentDirectory': contenturl = service.find('controlURL').text if contenturl.startswith('/'): end = url.find('/', 8) length = len(url) contenturl = url[:end-length] + contenturl else: end = url.rfind('/') length = len(url) contenturl = url[:end-length] + '/' + contenturl itemurl = build_url({'mode': 'server', 'contentdirectory': contenturl}) li = xbmcgui.ListItem(friendlyname, iconImage=iconurl) li.setArt({'thumb': iconurl, 'poster': iconurl, 'fanart': addon.getAddonInfo("path") + 'fanart.jpg'}) xbmcplugin.addDirectoryItem(handle=addon_handle, url=itemurl, listitem=li, isFolder=True) except Exception as e: printexception() pass setViewMode('servers') xbmcplugin.endOfDirectory(addon_handle, updateListing=force )
def __init__(self, rediscover=False, config_file=os.path.join(CONFIG_PATH, 'config.json')): """Initialize HEOS player.""" self.heosurl = 'heos://' with open(config_file) as json_data_file: config = json.load(json_data_file) self.host = config.get("host") self.pid = config.get("pid") self.player_name = config.get("player_name", config.get("main_player_name")) if self.player_name is None: logging.warn("No player name given.") raise Exception("No player name given.") # if host and pid is not known, detect the first HEOS device. if rediscover or (not self.host or not self.pid): logging.info( "Starting to discover your HEOS player '{}' in your local network" .format(self.player_name)) ssdp_list = ssdp.discover(self.URN_SCHEMA) self.telnet = None for response in ssdp_list: if response.st == self.URN_SCHEMA: try: self.host = re.match(r"http:..([^\:]+):", response.location).group(1) self.telnet = telnetlib.Telnet(self.host, 1255) self.pid = self._get_player(self.player_name) if self.pid: self.player_name = config.get( "player_name", config.get("main_player_name")) logging.info( "Found '{}' in your local network".format( self.player_name)) break except Exception as e: logging.error(e) pass if self.telnet == None: msg = "couldn't discover HEOS player with Simple Service Discovery Protocol (SSDP)." logging.error(msg) raise Exception(msg) else: logging.info("My cache says your HEOS player '{}' is at {}".format( self.player_name, self.host)) try: self.telnet = telnetlib.Telnet(self.host, 1255, timeout=TIMEOUT) except Exception as e: raise Exception("telnet failed") # check if we've found what we were looking for if self.host is None: logging.error("No HEOS player found in your local network") elif self.pid is None: logging.error("No player with name '{}' found!".format( self.player_name)) else: if self.login(user=config.get("user"), pw=config.get("pw")): self.user = config.get("user") # save config if (rediscover or config.get("pid") is None) and self.host and self.pid: logging.info("Save host and pid in {}".format(config_file)) config["pid"] = self.pid config["host"] = self.host with open(os.path.join(CONFIG_PATH, 'config.json'), "w") as json_data_file: json.dump(config, json_data_file, indent=2)
def on_scanButton_clicked(self, button, *args): mylocation = ssdp.discover("roku:ecp") Foundlabel.set_text(mylocation) with open("IPADDRESS.txt", "w") as text_file: print(mylocation, file=text_file) print(mylocation + "\n")
#/usr/bin/env python import ssdp import sys from pprint import pprint from fsapi import FSAPI services = ssdp.discover('urn:schemas-frontier-silicon-com:fs_reference:fsapi:1') if not len(services): print 'No device server found on network' sys.exit(1) print 'Found device server at "%s".' % (services[0].location) with FSAPI(services[0].location, 1234) as fs: #fs.volume = 10 #fs.mode = 'dab' #fs.power = True print 'FSAPI Endpoint is "%s".' % fs.get_fsapi_endpoint() pprint(fs) print 'Name: %s' % fs.friendly_name print 'Version: %s' % fs.version print 'Mute: %s' % fs.mute print 'Mode: %s' % fs.mode print 'Power: %s' % fs.power print 'Volume: %s' % fs.volume print 'Play status: %s' % fs.play_status print 'Artist name: %s' % fs.play_info_artist
from __future__ import print_function import ssdp import qhue import sys import urlparse def get_ip_address(location): parts = urlparse.urlparse(location) return parts.netloc.split(":")[0] if len(sys.argv) == 1: print("Looking for bridges... ", end='') services = ssdp.discover("") hue_bridges = [] for s in services: if s.hue_bridgeid != None: hue_bridges.append(s) print("done") if len(hue_bridges) == 1: hue_ip = get_ip_address(hue_bridges[0].location) else: print("Multiple bridges found:") for h in hue_bridges: print(" " + get_ip_address(h.location)) print("") print("Run this script with the IP address you want to use") exit(0)
#!/bin/env python2 from __future__ import print_function import ssdp import qhue import sys import urlparse def get_ip_address(location): parts = urlparse.urlparse(location) return parts.netloc.split(":")[0] if len(sys.argv) == 1: print("Looking for bridges... ", end='') services = ssdp.discover("") hue_bridges = [] for s in services: if s.hue_bridgeid != None: hue_bridges.append(s) print("done") if len(hue_bridges) == 1: hue_ip = get_ip_address(hue_bridges[0].location) else: print("Multiple bridges found:") for h in hue_bridges: print(" " + get_ip_address(h.location)) print("") print("Run this script with the IP address you want to use") exit(0) else:
def discover_devices(timeout=5, logger=_LOGGER): """Discover devices supporting Sony Audio Control API using SSDP Parameters: timeout -- timeout for SSDP broadcast (defaults to 5) logger -- logger to use for errors (defaults to root logger) """ devices = [] # XML namespaces from the Sony STR-DN1070 device descriptor XML file # Note: hopefully all Sony devices use the same namespaces ns = { "upnp": "urn:schemas-upnp-org:device-1-0", "av": "urn:schemas-sony-com:av", "dlna": "urn:schemas-dlna-org:device-1-0", "pnpx": "http://schemas.microsoft.com/windows/pnpx/2005/11", "df": "http://schemas.microsoft.com/windows/2008/09/devicefoundation", "ms": "urn:schemas-microsoft-com:WMPNSS-1-0" } # discover devices via the SSDP M-SEARCH method responses = ssdp.discover(_SSDP_SEARCH_TARGET, timeout=timeout) logger.debug("SSDP discovery returned %i devices.", len(responses)) # iterate through the responses for response in responses: # Retrieve the XML from the specified URL try: response = requests.get(response.location) # If the device answered SSDP broadcast with the location, the XML page at the location # should be available so log and terminate on all errors except: logger.error( "Unexpected error occurred retrieving device info: %s", sys.exc_info()[0]) raise # parse the XML from the response root = ET.fromstring(response.text) # extract the Sony Audio Control API DeviceInfo node from the XML apiNode = root.find(".//av:X_ScalarWebAPI_DeviceInfo", ns) # if the DeviceInfo node for the Sony Audio Control API was found, make sure # the device supports all of the required services if apiNode is not None: # extract the supported services from the DeviceInfo nodes services = [] for serviceType in apiNode.find( "av:X_ScalarWebAPI_ServiceList", ns).findall("av:X_ScalarWebAPI_ServiceType", ns): services.append(serviceType.text) # check for system, audio, and avContent service support if all(s in services for s in ("system", "audio", "avContent")): # extract the elements we need from the XML string id = root.find(".//upnp:UDN", ns).text[ -6:] # the last 6 digits of the "node" from the uuid (hex) name = root.find(".//upnp:friendlyName", ns).text model = root.find(".//upnp:modelName", ns).text apiVer = apiNode.find("av:X_ScalarWebAPI_Version", ns).text apiURL = apiNode.find("av:X_ScalarWebAPI_BaseURL", ns).text logger.debug( "Sony Audio Control API device found in discover - ID: %s, Name: %s, Model: %s", id, name, model) # append to device list devices.append({ "id": id, "name": name, "model": model, "apiVer": apiVer, "apiURL": apiURL }) return devices
# we have taken so far so they can go to the cloud. longest_capture_time = 60.0 window_after_last_capture = 60.0 # after receiving "avgwindow" images from the stream, I average the deltas # and compare against for the threshold avgwindow = 8 # if the diff is higher than the last average * "motion_threshold", I take # pictures motion_threshold = 1.75 found_pana = False while [1]: serv = ssdp.discover('urn:schemas-upnp-org:device:MediaServer:1') if serv: print('found service discover') for target in serv: print(target.server) if (target.server.find("Panasonic-UPnP") != -1): (cam_ip, cam_port) = urllib.parse.urlparse( target.location).netloc.split(':') found_pana = True print('found pana') break if found_pana: break cam_port = int(cam_port) print('found camera, IP: %s' % cam_ip) stream_flag = True