本文整理汇总了Python中twisted.logger.Logger.debug方法的典型用法代码示例。如果您正苦于以下问题:Python Logger.debug方法的具体用法?Python Logger.debug怎么用?Python Logger.debug使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.logger.Logger
的用法示例。
在下文中一共展示了Logger.debug方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HouseStatus
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class HouseStatus(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:HouseStatus:1'
serviceId = 'urn:schemas-upnp-org:serviceId:HouseStatus'
serviceUrl = 'house'
type = 'House'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application'):
'''
Constructor
'''
super(HouseStatus, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.houses.append(self)
self.occupancystate = 'Indeterminate'
self.activitylevel = 'Regular'
self.dormancylevel = 'Regular'
def upnp_event(self, evt, var):
self.log.debug('away event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例2: Volume
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Volume(Service):
version = (1, 0)
serviceType = "urn:av-openhome-org:service:Volume:1"
serviceId = "urn:av-openhome-org:serviceId:Volume"
serviceUrl = "Volume"
type = 'Volume'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application'):
super(Volume, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.oh_eventVOLUME = self.upnp_event
self.volumemax = self.client.max_volume
self.volumeunity = 3
self.volume = self.volumemax
self.volumesteps = self.volumemax
self.volumemillidbperstep = 600
self.balancemax = 10
self.balance = 0
self.fademax = 10
self.fade = 0
self.mute = 0
def upnp_event(self, evt, var):
self.log.debug('volume event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例3: FanOperatingMode
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class FanOperatingMode(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:HVAC_FanOperatingMode:1'
serviceId = 'urn:schemas-upnp-org:serviceId:HVAC_FanOperatingMode'
serviceUrl = 'fanmode'
type = 'FanOperating'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application', system=False):
'''
Constructor
'''
super(FanOperatingMode, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.UPNP_fan_event = self.upnp_event
self.mode = 'ContinuousOn'
self.fanstatus = 'Off'
self.name = name
def upnp_event(self, evt, var):
self.log.debug('fan event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例4: TemperatureSensor
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class TemperatureSensor(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:TemperatureSensor:1'
serviceId = 'urn:schemas-upnp-org:serviceId:TemperatureSensor'
serviceUrl = 'temp'
type = 'Temperature'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application', system=False):
'''
Constructor
'''
super(TemperatureSensor, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
if system:
self.application = 'Outdoor'
else:
self.application = 'Room'
self.client.UPNP_Temp_event = self.upnp_event
self.currenttemperature = 2000
self.name = name
def upnp_event(self, evt, var):
self.log.debug('temp event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例5: i2cProtocol
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class i2cProtocol(LineOnlyReceiver):
def __init__(self):
self.log = Logger()
self.__funcs = {}
def connectionMade(self):
self.log.debug('i2c connected')
def lineReceived(self, line):
line = line.strip()
called = line[:9].lstrip('0')
onoff = bool(int(line[-1]))
try:
call = self.__funcs[called]
except:
return
else:
call(onoff)
def send_on(self):
self.transport.write(self.factory.on_msg)
def send_off(self):
self.transport.write(self.factory.off_msg)
def addCallback(self, name, func):
self.__funcs[name] = func
def remCallback(self, name):
try:
del self.__funcs[name]
except KeyError:
return
示例6: Demo_light_factory
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Demo_light_factory(ReconnectingClientFactory, Client):
def __init__(self, long_address=b'\x00\x00\x00\x00\x00\x00\xFF\xFF',
address=b'\xFF\xFE', pin=0,
api_level=1, net_type=None, stateless=True):
self.long_address = long_address
self.address = address
self._pin = pin
self.pin = 'dio-' + bytes(pin)
self.status = False
self.proto = None
self.log = Logger()
self.callback = self.receive
self.stateless = stateless
'''
Remote functions
'''
def r_set_target(self, value):
if value is not self.status:
if value is True:
self.proto.remote_at(dest_addr_long=self.long_address,
command=b'D%d' % self._pin,
parameter=b'\x05')
else:
self.proto.remote_at(dest_addr_long=self.long_address,
command=b'D%d' % self._pin,
parameter=b'\x04')
if self.stateless:
self.status = value
self.event(value, 'status')
def r_get_target(self):
return self.status
def r_get_status(self):
return self.status
def set_status(self, status):
if status is not self.status:
self.log.debug('%r --> %s' % (self.long_address,
'jour!' if status else 'nuit!'))
self.status = status
self.event(status, 'status')
def receive(self, data):
if 'samples' in data:
for sample in data['samples']:
if self.pin in sample:
self.set_status(sample[self.pin])
elif 'parameter' in data:
for sample in data['parameter']:
if self.pin in sample:
self.set_status(sample[self.pin])
示例7: Fake_HE_endpoint
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Fake_HE_endpoint(object):
bus = None
clients = {}
def __init__(self, reactor, bus_addr, addr, speed):
self.random = False
self.log = Logger()
self.reactor = reactor
self.bus_addr = bus_addr
self.pair = addr
self.speed = speed
self.running = False
def connect(self, clientFactory):
proto = clientFactory.proto
proto.transport = self
if clientFactory.addr not in self.clients:
self.clients.update({clientFactory.addr: proto})
if not self.bus:
r = task.LoopingCall(self.check)
r.start(20)
clientFactory.doStart()
return defer.succeed(None)
def check(self):
if not self.running:
for client in self.clients.values():
client.connectionMade()
self.running = True
self.bus = True
self.random = not self.random
l = '162342660' + str(int(self.random))
ll = '334455660' + str(int(not self.random))
if l[:-1] in self.clients:
self.clients[l[:-1]].lineReceived(l)
if ll[:-1] in self.clients:
self.clients[ll[:-1]].lineReceived(ll)
def write(self, msg):
t = []
if len(msg) < 11:
for n in msg:
t.append(ord(n))
else:
raise Exception('too much data')
self.log.debug('send %s to i2c link' % t)
示例8: serialLineProtocol
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class serialLineProtocol(LineOnlyReceiver):
def __init__(self):
self.log = Logger()
self.__callbacks = {}
def connectionMade(self):
self.log.debug('serial connected')
def lineReceived(self, line):
for name in self.__callbacks:
self.__callbacks[name](line)
def send(self, data):
self.transport.write(data)
def addCallback(self, name, func):
self.__callbacks.update({name: func})
def remCallback(self, name):
if name in self.__callbacks:
del self.__callbacks[name]
示例9: Rest
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Rest(object):
def __init__(
self,
host='https://developer-api.nest.com',
token=None,
event_handler=None,
net_type='lan'):
self.log = Logger()
self.host = host
self.token = token
self.event_handler = event_handler
self.pool = HTTPConnectionPool(reactor, persistent=True)
self.loc = None
self.reconnect = False
self.fail_count = 0
if event_handler:
self.reconnect = True
d = self.request(headers={'User-Agent': ['onDemand Rest Client'],
'Accept': ['text/event-stream']})
d.addCallback(self.on_disconnect)
def __getattr__(self, name):
try:
super(Rest, self).__getattr__(name)
except AttributeError:
return RestCall(self, name)
def on_disconnect(self, reason):
if not reason:
reason = {'reason': 'no_message'}
self.log.critical(
'disconnected: {reason}', reason=reason['reason'])
if self.fail_count > 10:
self.log.error('Max error count reached, aborting connection')
def test_connectivity(count):
if self.fail_count == count:
self.fail_count = 0
self.fail_count += 1
c = self.fail_count
reactor.callLater(10, test_connectivity, c) # @UndefinedVariable
if self.reconnect:
d = self.request(headers={'User-Agent': ['onDemand Rest Client'],
'Accept': ['text/event-stream']})
d.addCallback(self.on_disconnect)
def request(self, method='GET',
path='',
headers={'User-Agent': ['onDemand/1.0 (Rest_Client)'],
'Accept': ['application/json']},
body=None):
data = None
if self.loc:
host = '/'.join((self.loc, path))
else:
host = '/'.join((self.host, path))
if self.token:
host += '?auth=' + self.token
if body:
headers.update({'Content-Type': ['application/json']})
data = FileBodyProducer(StringIO(json.dumps(body)))
agent = RedirectAgent(Agent(reactor, pool=self.pool))
d = agent.request(method, host, Headers(headers), data)
def cbFail(fail):
if hasattr(fail.value, 'response'):
if hasattr(fail.value.response, 'code'):
if fail.value.response.code == 307:
loc = fail.value.response.headers.getRawHeaders(
'location')
new = urlparse(loc[0])
newhost = '://'.join((new.scheme, new.netloc))
if newhost == self.host:
self.loc = None
else:
self.loc = newhost
self.log.debug('redirect: %s' % self.loc)
data = FileBodyProducer(StringIO(json.dumps(body)))
d = agent.request(
method, loc[0], Headers(headers), data)
d.addCallbacks(cbRequest, cbFail)
return d
elif fail.value.response.code == 404 and self.loc:
self.loc = None
host = '/'.join((self.host, path))
if self.token:
host += '?auth=' + self.token
d = self.request(method, host, Headers(headers), body)
d.addCallbacks(cbRequest, cbFail)
return d
else:
print(dir(fail.value))
print(fail.value.message)
print(fail.value.args)
self.log.error('unhandled failure: %s -- %s' % (
#.........这里部分代码省略.........
示例10: IRCd
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
#.........这里部分代码省略.........
self._loadModuleData(module)
for moduleName in self.config["modules"]:
if moduleName not in self.loadedModules:
self.log.warn("The module {module} failed to load.", module=moduleName)
def loadModule(self, moduleName):
"""
Loads a module of the specified name.
Raises ModuleLoadError if the module cannot be loaded.
If the specified module is currently being unloaded, returns the
DeferredList specified by the module when it was unloading with a
callback to try to load the module again once it succeeds.
"""
if moduleName in self._unloadingModules:
deferList = self._unloadingModules[moduleName]
deferList.addCallback(self._tryLoadAgain, moduleName)
return deferList
for module in getPlugins(IModuleData, txircd.modules):
if module.name == moduleName:
rebuild(importlib.import_module(module.__module__)) # getPlugins doesn't recompile modules, so let's do that ourselves.
self._loadModuleData(module)
self.log.info("Loaded module {module}.", module=moduleName)
break
def _tryLoadAgain(self, _, moduleName):
self.loadModule(moduleName)
def _loadModuleData(self, module):
if not IModuleData.providedBy(module):
raise ModuleLoadError ("???", "Module does not implement module interface")
if not module.name:
raise ModuleLoadError ("???", "Module did not provide a name")
if module.name in self.loadedModules:
self.log.debug("Not loading {module.name} because it's already loaded", module=module)
return
self.log.debug("Beginning to load {module.name}...", module=module)
module.hookIRCd(self)
try:
module.verifyConfig(self.config)
except ConfigError as e:
raise ModuleLoadError(module.name, e)
self.log.debug("Loading hooks from {module.name}...", module=module)
moduleData = {
"channelmodes": module.channelModes(),
"usermodes": module.userModes(),
"actions": module.actions(),
"usercommands": module.userCommands(),
"servercommands": module.serverCommands()
}
newChannelModes = ({}, {}, {}, {})
newChannelStatuses = {}
newUserModes = ({}, {}, {}, {})
newActions = {}
newUserCommands = {}
newServerCommands = {}
common = False
self.log.debug("Processing hook data from {module.name}...", module=module)
for mode in moduleData["channelmodes"]:
if mode[0] in self.channelModeTypes:
raise ModuleLoadError (module.name, "Tries to implement channel mode +{} when that mode is already implemented.".format(mode[0]))
if not IMode.providedBy(mode[2]):
raise ModuleLoadError (module.name, "Returns a channel mode object (+{}) that doesn't implement IMode.".format(mode[0]))
if mode[1] == ModeType.Status:
if mode[4] in self.channelStatusSymbols:
示例11: Discord
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Discord(IRCClient):
nickname = "discord"
realname = "Discord"
username = "discord"
versionName = "Discord"
versionNum = "0.01"
magicFile = "true.txt"
def __init__(self, accessList):
self.logger = Logger(observer=textFileLogObserver(sys.stdout))
self.accessList = [nick.lower() for nick in accessList]
if not os.path.exists(self.magicFile):
self.logger.info("Creating magic file")
try:
with open(self.magicFile, "a"):
pass
except Exception as ex:
self.logger.error("Unable to create magic file! {0}".format(ex.message))
reactor.stop()
self.markovGenerator = pymarkov.MarkovChainGenerator(self.magicFile)
self.channels = []
self.channelPhrasers = {}
self.logger.debug("Discord initialized")
# Maybe add hook/plugin system here?
self.commands = Commands.Commands(self)
def removeChannel(self, channel):
try:
self.channels.remove(channel)
self.channelPhrasers[channel].stop()
del self.channelPhrasers[channel]
except:
self.logger.error("Error removing {channel} from collection", channel=channel)
def insertPhrase(self, phrase):
try:
with open(self.magicFile, "a") as magicFile:
magicFile.write("{0}\n".format(phrase))
try:
file, ext = os.path.splitext(self.magicFile)
os.remove("{0}-pickled{1}".format(file, ext))
# Simply re-populating the dictionary isn't enough for some reason
self.markovGenerator = pymarkov.MarkovChainGenerator(self.magicFile, 2)
except IOError as ex:
self.logger.error("Unable to delete pickled file. {0}".format(ex.message))
except Exception as ex:
self.logger.error("Unable to insert phrase into magic file! {0}".format(ex.message))
def kickedFrom(self, channel, kicker, message):
self.removeChannel(channel)
self.logger.info("Kicked from {channel} by {kicker}", channel=channel, kicker=kicker)
def left(self, channel):
self.removeChannel(channel)
self.logger.info("Left {channel}", channel=channel)
def handleMessage(self, user, channel, message):
senderNickname = user.split("!")[0]
if message.startswith("~reload") and senderNickname in self.accessList:
self.logger.info("Reloading commands module")
self.say(channel, "Reloading.")
try:
commandsModule = reload(Commands)
self.commands = commandsModule.Commands(self)
except Exception as ex:
self.say(channel, "Failed to load commands module - {0}".format(ex.message))
elif message.startswith("~"):
# Don't log commands to the brain
commandMessage = message[1:]
self.commands.handleCommand(user, channel, commandMessage)
else:
self.logger.info("Adding {message!r} to brain", message=message)
# Avoid storing anything with the bot's name in it
#.........这里部分代码省略.........
示例12: MpdProtocol
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class MpdProtocol(LineReceiver):
"""
Twisted protocol to control remote mpd server
"""
def __init__(self):
"""
doc
"""
self.log = Logger()
self.delimiter = "\n"
self.deferreds = []
self.buff = {}
self.idle = False
self.list_index = 0
def connectionLost(self, reason):
self.log.error("connection lost : {reason}", reason=reason)
self._event({"changed": "disconnected"})
self.idle = False
try:
d = self.deferreds.pop(0)
except:
pass
else:
d.errback(reason)
def connectionMade(self):
self.log.debug("connected")
def addCallback(self, d):
self.deferreds.append(d)
def noidle(self):
d = defer.Deferred()
d.addCallback(lambda ignored: ignored)
self.deferreds.insert(0, d)
self.sendLine("noidle")
self.idle = False
# print('noidle')
def set_idle(self):
self.sendLine("idle")
self.idle = True
# print('idle')
def lineReceived(self, line):
# print(line)
if line.startswith("OK MPD"):
self._event({"changed": "connected"})
elif line.startswith("OK"):
# print('deferred length: %d' % len(self.deferreds))
self.list_index = 1
try:
d = self.deferreds.pop(0)
except:
self.set_idle()
self._event(self.buff)
self.buff = {}
return
else:
d.callback(self.buff)
self.buff = {}
elif line.startswith("ACK"):
# print('deferred length: %d' % len(self.deferreds))
try:
d = self.deferreds.pop(0)
except:
self.set_idle()
self._event({"Error": line.split("}")[1]})
self.buff = {}
return
else:
d.errback(Exception(line.split("}")[1]))
self.buff = {}
else:
if len(line) > 0:
k = line.split(":")[0]
if isinstance(self.buff, list):
if k in self.buff[self.list_index]:
self.list_index += 1
self.buff.append({})
self.buff[self.list_index].update({k: " ".join(line.split()[1:])})
else:
if k in self.buff:
self.buff = [self.buff]
self.list_index = 1
self.buff.append({k: " ".join(line.split()[1:])})
# if str(self.list_index) + k in self.buff:
# self.list_index += 1
# self.buff.update(
# {str(self.list_index) + line.split(':')[0]:
# ' '.join(line.split()[1:])})
else:
self.buff.update({k: " ".join(line.split()[1:])})
return
if len(self.deferreds) == 0:
self.set_idle()
示例13: EventSubscription
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class EventSubscription(object):
__slots__ = ['sid',
'callback',
'timeout',
'last_subscribe',
'next_notify_key',
'expired',
'__dict__']
def __init__(self, sid, callback, timeout):
self.log = Logger()
self.sid = sid
self.callback_addr = callback
self.timeout = timeout
self.last_subscribe = time.time()
self.next_notify_key = 0
self.expired = False # subscription has been flagged for deletion
self.agent = Agent(reactor)
self.pending_events = {}
self.pending = False
def _increment_notify_key(self):
if self.next_notify_key >= 4294967295:
self.next_notify_key = 0
else:
self.next_notify_key += 1
def check_expiration(self):
if self.expired is True:
return True
if time.time() > self.last_subscribe + self.timeout:
self.expired = True
return True
return False
def send_notify(self):
self.pending = False
if len(self.pending_events) == 0:
return
PREFIX = "{urn:schemas-upnp-org:event-1-0}"
_propertyset = et.Element(
'propertyset',
nsmap={'e': 'urn:schemas-upnp-org:event-1-0'})
# _propertyset = et.Element(
# 'e:propertyset',
# attrib={'xmlns:e': 'urn:schemas-upnp-org:event-1-0'})
for prop in self.pending_events.values():
if prop.namespace is not None:
et.register_namespace('e', prop.namespace)
_property = et.SubElement(_propertyset, PREFIX + 'property')
# log.msg('Child xml = %s' % prop.value)
# _property.append(make_element(prop.name, str(prop.value)))
try:
evt = et.Element(prop.name)
if prop.name == 'LastChange':
if prop.namespace is None:
ev = et.Element('Event')
else:
ev = et.Element('Event',
attrib={'xmlns': prop.namespace})
inst = et.Element('InstanceID', attrib={'val': "0"})
prefix = ''
for n in prop.value:
if 'namespace' in prop.value[n]:
prefix = '%s:' % n[0]
et.register_namespace(prefix,
prop.value[n]['namespace'])
if 'attrib' in prop.value[n]:
attr = prop.value[n]['attrib']
else:
attr = {}
attr.update(
{'val': str(prop.value[n]['value'])
.decode('utf-8')})
var = et.Element(prefix + n, attrib=attr)
# var.text = str(prop.value[n]['value'])
inst.append(var)
ev.append(inst)
# evt.append(ev)
evt.text = et.tostring(ev)
else:
# log.err('%s - %s' % (prop.name, prop.value))
evt.text = str(prop.value).decode('utf-8')
_property.append(evt)
except:
self.log.debug(
'Malformed XML Event: %s' % dir(prop))
return
_propertyset.append(_property)
headers = {
'NT': ['upnp:event'],
'NTS': ['upnp:propchange'],
'SID': [self.sid],
'SEQ': [str(self.next_notify_key)],
'Content-Type': ['text/xml']
}
data = StringIO(''.join(('<?xml version="1.0" ',
#.........这里部分代码省略.........
示例14: XmppEvent
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class XmppEvent(object):
def __init__(self, nodeId, parent, pubsub_addr):
self.log = Logger()
self.nodeId = nodeId
self.parent = parent
self.addr = pubsub_addr
def publish(self, event):
if len(self.parent.active_controllers) == 0:
# self.log.debug('event cancelled')
self.parent.registrations = []
return
def success(res):
# print('event sent')
if res['type'] == 'error':
self.log.error('Publish Event failed :%s' % res.toXml())
else:
if 'Id' in res.children[0].children[0]['node']:
self.log.debug('Event Published: %s' % res.toXml())
name, data = event
if name == 'Seconds':
return
iq = IQ(self.parent.xmlstream, 'set')
ps = domish.Element(('http://jabber.org/protocol/pubsub', 'pubsub'))
publish = domish.Element((None, 'publish'))
publish['node'] = '/'.join((self.nodeId, name))
item = domish.Element((None, 'item'))
propertyset = domish.Element(
('urn:schemas-upnp-org:event-1-0', 'propertyset'),
localPrefixes={'e': 'urn:schemas-upnp-org:event-1-0'})
prop = domish.Element((None, 'e:property'))
evt = domish.Element((None, name))
if isinstance(data.value, dict):
ev = domish.Element((data.namespace, 'Event'))
inst = domish.Element((None, 'InstanceID'))
inst['val'] = '0'
for k, v in data.value.items:
if 'namespace' in v:
var = domish.Element((v['namespace'], k))
else:
var = domish.Element((None, k))
if 'attrib' in v:
attr = v['attrib']
else:
attr = {}
value = v['value']
if isinstance(value, bool):
value = int(value)
attr.update(
{'val': str(value)
.decode('utf-8')})
for attname, attval in attr:
var[attname] = attval
inst.addChild(var)
ev.addChild(inst)
evt.addChild(ev)
else:
# print(str(data.value).decode('utf-8'))
if isinstance(data.value, bool):
data.value = int(data.value)
evt.addContent(str(data.value).decode('utf-8'))
prop.addChild(evt)
propertyset.addChild(prop)
item.addChild(propertyset)
publish.addChild(item)
ps.addChild(publish)
iq.addChild(ps)
iq.addCallback(success)
iq.send(to=self.addr)
示例15: Controller
# 需要导入模块: from twisted.logger import Logger [as 别名]
# 或者: from twisted.logger.Logger import debug [as 别名]
class Controller(service.MultiService):
targets = {}
services = []
binary_light_list = []
hvac_list = []
media_player_list = []
messager = None
server_list = []
shutter_list = []
camera_list = []
multiscreen_list = []
dimmable_light_list = []
ambi_light_list = []
event_catcher = None
cloud_event_catcher = None
subscriptions = {}
subscriptions_cloud = {}
searchables = {}
ready_to_close = False
current_device = None
cloud = False
lan = False
agent = None
def __init__(
self, parent=None, searchables=None, xmldir=None,
network='lan', cloud_user=None, cloud_servers=[],
logger=None, uid=None, messager=None):
self.connected = False
self.messager = messager
self.app_paused = False
self.fail_count = 0
if not logger:
self.log = Logger()
else:
self.log = logger
self.log.debug('UPnP controller starts')
self.xmldir = xmldir
self.devices = {}
self._services = {}
self.parent = parent
# self.amp = ControllerAmp(self)
if uid:
self.uuid = uid
else:
self.uuid = str(
uuid.uuid5(
uuid.NAMESPACE_DNS,
socket.gethostname() + 'onDemand_Controller'))
if searchables:
for typ in searchables:
self.searchables.update({typ[0]: typ[1]})
# print(self.searchables)
else:
self.searchables = {'upnp:rootdevice': self.log.debug}
if network in ('lan', 'both'):
self.log.debug('UPnP classic enabled')
self.lan = True
self.listener = ssdp.SSDP_Listener(self)
self.mcast = internet.MulticastServer( # @UndefinedVariable
SSDP_PORT,
self.listener,
listenMultiple=True,
interface=SSDP_ADDR_V4)
self.mcast.setServiceParent(self)
self.ssdp_cli = ssdp.SSDP_Client(
self, get_default_v4_address(), device=False)
self.ucast = internet.UDPServer( # @UndefinedVariable
0, self.ssdp_cli, self.ssdp_cli.interface)
self.ucast.setServiceParent(self)
# self.agent = Agent(reactor)
if network in ('cloud', 'both'):
if cloud_user:
self.log.debug('UPnP Cloud enabled')
self.cloud = True
self._jid, secret = cloud_user
self.users = {self._jid: {'state': True}}
for user in cloud_servers:
self.users.update({user: {'state': False}})
self.hosts = {}
self.resourcepart = ''.join((
'urn:schemas-upnp-org:cloud-1-0:ControlPoint:1:uuid:',
self.uuid))
full_jid = ''.join(
(self._jid, '/', self.resourcepart))
self.jid = jid = JID(full_jid)
self.reactor = reactor
f = client.XMPPClientFactory(jid, secret)
f.addBootstrap(
xmlstream.STREAM_CONNECTED_EVENT, self.cloud_connected)
f.addBootstrap(
xmlstream.STREAM_END_EVENT, self.cloud_disconnected)
f.addBootstrap(
xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(
xmlstream.INIT_FAILED_EVENT, self.cloud_failed)
self.connector = endpoints.HostnameEndpoint(
reactor, jid.host, 5222)
self.factory = f
# factory = Factory()
#.........这里部分代码省略.........