code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Parse bounce messages generated by Postfix. This also matches something called `Keftamail' which looks just like Postfix bounces with the word Postfix scratched out and the word `Keftamail' written in in crayon. It also matches something claiming to be `The BNS Postfix program', and `SMTP_Gateway'. Everybody's gotta be different, huh? """ import re from cStringIO import StringIO def flatten(msg, leaves): # give us all the leaf (non-multipart) subparts if msg.is_multipart(): for part in msg.get_payload(): flatten(part, leaves) else: leaves.append(msg) # are these heuristics correct or guaranteed? pcre = re.compile(r'[ \t]*the\s*(bns)?\s*(postfix|keftamail|smtp_gateway)', re.IGNORECASE) rcre = re.compile(r'failure reason:$', re.IGNORECASE) acre = re.compile(r'<(?P<addr>[^>]*)>:') def findaddr(msg): addrs = [] body = StringIO(msg.get_payload()) # simple state machine # 0 == nothing found # 1 == salutation found state = 0 while 1: line = body.readline() if not line: break # preserve leading whitespace line = line.rstrip() # yes use match to match at beginning of string if state == 0 and (pcre.match(line) or rcre.match(line)): state = 1 elif state == 1 and line: mo = acre.search(line) if mo: addrs.append(mo.group('addr')) # probably a continuation line return addrs def process(msg): if msg.get_content_type() not in ('multipart/mixed', 'multipart/report'): return None # We're looking for the plain/text subpart with a Content-Description: of # `notification'. leaves = [] flatten(msg, leaves) for subpart in leaves: if subpart.get_content_type() == 'text/plain' and \ subpart.get('content-description', '').lower() == 'notification': # then... return findaddr(subpart) return None
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Postfix.py
Postfix.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Recognizes simple heuristically delimited bounces.""" import re import email.Iterators def _c(pattern): return re.compile(pattern, re.IGNORECASE) # This is a list of tuples of the form # # (start cre, end cre, address cre) # # where `cre' means compiled regular expression, start is the line just before # the bouncing address block, end is the line just after the bouncing address # block, and address cre is the regexp that will recognize the addresses. It # must have a group called `addr' which will contain exactly and only the # address that bounced. PATTERNS = [ # sdm.de (_c('here is your list of failed recipients'), _c('here is your returned mail'), _c(r'<(?P<addr>[^>]*)>')), # sz-sb.de, corridor.com, nfg.nl (_c('the following addresses had'), _c('transcript of session follows'), _c(r'<(?P<fulladdr>[^>]*)>|\(expanded from: <?(?P<addr>[^>)]*)>?\)')), # robanal.demon.co.uk (_c('this message was created automatically by mail delivery software'), _c('original message follows'), _c('rcpt to:\s*<(?P<addr>[^>]*)>')), # s1.com (InterScan E-Mail VirusWall NT ???) (_c('message from interscan e-mail viruswall nt'), _c('end of message'), _c('rcpt to:\s*<(?P<addr>[^>]*)>')), # Smail (_c('failed addresses follow:'), _c('message text follows:'), _c(r'\s*(?P<addr>\S+@\S+)')), # newmail.ru (_c('This is the machine generated message from mail service.'), _c('--- Below the next line is a copy of the message.'), _c('<(?P<addr>[^>]*)>')), # turbosport.com runs something called `MDaemon 3.5.2' ??? (_c('The following addresses did NOT receive a copy of your message:'), _c('--- Session Transcript ---'), _c('[>]\s*(?P<addr>.*)$')), # usa.net (_c('Intended recipient:\s*(?P<addr>.*)$'), _c('--------RETURNED MAIL FOLLOWS--------'), _c('Intended recipient:\s*(?P<addr>.*)$')), # hotpop.com (_c('Undeliverable Address:\s*(?P<addr>.*)$'), _c('Original message attached'), _c('Undeliverable Address:\s*(?P<addr>.*)$')), # Another demon.co.uk format (_c('This message was created automatically by mail delivery'), _c('^---- START OF RETURNED MESSAGE ----'), _c("addressed to '(?P<addr>[^']*)'")), # Prodigy.net full mailbox (_c("User's mailbox is full:"), _c('Unable to deliver mail.'), _c("User's mailbox is full:\s*<(?P<addr>[^>]*)>")), # Microsoft SMTPSVC (_c('The email below could not be delivered to the following user:'), _c('Old message:'), _c('<(?P<addr>[^>]*)>')), # Yahoo on behalf of other domains like sbcglobal.net (_c('Unable to deliver message to the following address\(es\)\.'), _c('--- Original message follows\.'), _c('<(?P<addr>[^>]*)>:')), # googlemail.com (_c('Delivery to the following recipient failed'), _c('----- Original message -----'), _c('^\s*(?P<addr>[^\s@]+@[^\s@]+)\s*$')), # kundenserver.de (_c('A message that you sent could not be delivered'), _c('^---'), _c('<(?P<addr>[^>]*)>')), # another kundenserver.de (_c('A message that you sent could not be delivered'), _c('^---'), _c('^(?P<addr>[^\s@]+@[^\s@:]+):')), # thehartford.com (_c('Delivery to the following recipients failed'), # this one may or may not have the original message, but there's nothing # unique to stop on, so stop on the first line of at least 3 characters # that doesn't start with 'D' (to not stop immediately) and has no '@'. _c('^[^D][^@]{2,}$'), _c('^\s*(?P<addr>[^\s@]+@[^\s@]+)\s*$')), # and another thehartfod.com/hartfordlife.com (_c('^Your message\s*$'), _c('^because:'), _c('^\s*(?P<addr>[^\s@]+@[^\s@]+)\s*$')), # kviv.be (InterScan NT) (_c('^Unable to deliver message to'), _c(r'\*+\s+End of message\s+\*+'), _c('<(?P<addr>[^>]*)>')), # earthlink.net supported domains (_c('^Sorry, unable to deliver your message to'), _c('^A copy of the original message'), _c('\s*(?P<addr>[^\s@]+@[^\s@]+)\s+')), # ademe.fr (_c('^A message could not be delivered to:'), _c('^Subject:'), _c('^\s*(?P<addr>[^\s@]+@[^\s@]+)\s*$')), # andrew.ac.jp (_c('^Invalid final delivery userid:'), _c('^Original message follows.'), _c('\s*(?P<addr>[^\s@]+@[^\s@]+)\s*$')), # E500_SMTP_Mail_Service@lerctr.org (_c('------ Failed Recipients ------'), _c('-------- Returned Mail --------'), _c('<(?P<addr>[^>]*)>')), # cynergycom.net (_c('A message that you sent could not be delivered'), _c('^---'), _c('(?P<addr>[^\s@]+@[^\s@)]+)')), # LSMTP for Windows (_c('^--> Error description:\s*$'), _c('^Error-End:'), _c('^Error-for:\s+(?P<addr>[^\s@]+@[^\s@]+)')), # Qmail with a tri-language intro beginning in spanish (_c('Your message could not be delivered'), _c('^-'), _c('<(?P<addr>[^>]*)>:')), # socgen.com (_c('Your message could not be delivered to'), _c('^\s*$'), _c('(?P<addr>[^\s@]+@[^\s@]+)')), # dadoservice.it (_c('Your message has encountered delivery problems'), _c('Your message reads'), _c('addressed to\s*(?P<addr>[^\s@]+@[^\s@)]+)')), # gomaps.com (_c('Did not reach the following recipient'), _c('^\s*$'), _c('\s(?P<addr>[^\s@]+@[^\s@]+)')), # EYOU MTA SYSTEM (_c('This is the deliver program at'), _c('^-'), _c('^(?P<addr>[^\s@]+@[^\s@<>]+)')), # A non-standard qmail at ieo.it (_c('this is the email server at'), _c('^-'), _c('\s(?P<addr>[^\s@]+@[^\s@]+)[\s,]')), # pla.net.py (MDaemon.PRO ?) (_c('- no such user here'), _c('There is no user'), _c('^(?P<addr>[^\s@]+@[^\s@]+)\s')), # Next one goes here... ] def process(msg, patterns=None): if patterns is None: patterns = PATTERNS # simple state machine # 0 = nothing seen yet # 1 = intro seen addrs = {} # MAS: This is a mess. The outer loop used to be over the message # so we only looped through the message once. Looping through the # message for each set of patterns is obviously way more work, but # if we don't do it, problems arise because scre from the wrong # pattern set matches first and then acre doesn't match. The # alternative is to split things into separate modules, but then # we process the message multiple times anyway. for scre, ecre, acre in patterns: state = 0 for line in email.Iterators.body_line_iterator(msg): if state == 0: if scre.search(line): state = 1 if state == 1: mo = acre.search(line) if mo: addr = mo.group('addr') if addr: addrs[mo.group('addr')] = 1 elif ecre.search(line): break if addrs: break return addrs.keys()
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/SimpleMatch.py
SimpleMatch.py
# Copyright (C) 2001-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Recognizes simple heuristically delimited warnings.""" from mailman.Bouncers.BouncerAPI import Stop from mailman.Bouncers.SimpleMatch import _c from mailman.Bouncers.SimpleMatch import process as _process # This is a list of tuples of the form # # (start cre, end cre, address cre) # # where `cre' means compiled regular expression, start is the line just before # the bouncing address block, end is the line just after the bouncing address # block, and address cre is the regexp that will recognize the addresses. It # must have a group called `addr' which will contain exactly and only the # address that bounced. patterns = [ # pop3.pta.lia.net (_c('The address to which the message has not yet been delivered is'), _c('No action is required on your part'), _c(r'\s*(?P<addr>\S+@\S+)\s*')), # This is from MessageSwitch. It is a kludge because the text that # identifies it as a warning only comes after the address. We can't # use ecre, because it really isn't significant, so we fake it. Once # we see the start, we know it's a warning, and we're going to return # Stop anyway, so we match anything for the address and end. (_c('This is just a warning, you do not need to take any action'), _c('.+'), _c('(?P<addr>.+)')), # Symantec_AntiVirus_for_SMTP_Gateways - see comments for MessageSwitch (_c('Delivery attempts will continue to be made'), _c('.+'), _c('(?P<addr>.+)')), # Next one goes here... ] def process(msg): if _process(msg, patterns): # It's a recognized warning so stop now return Stop else: return []
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/SimpleWarning.py
SimpleWarning.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Compuserve has its own weird format for bounces.""" import re import email dcre = re.compile(r'your message could not be delivered', re.IGNORECASE) acre = re.compile(r'Invalid receiver address: (?P<addr>.*)') def process(msg): # simple state machine # 0 = nothing seen yet # 1 = intro line seen state = 0 addrs = [] for line in email.Iterators.body_line_iterator(msg): if state == 0: mo = dcre.search(line) if mo: state = 1 elif state == 1: mo = dcre.search(line) if mo: break mo = acre.search(line) if mo: addrs.append(mo.group('addr')) return addrs
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Compuserve.py
Compuserve.py
# Copyright (C) 2002-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """sina.com bounces""" import re from email import Iterators acre = re.compile(r'<(?P<addr>[^>]*)>') def process(msg): if msg.get('from', '').lower() <> 'mailer-daemon@sina.com': print 'out 1' return [] if not msg.is_multipart(): print 'out 2' return [] # The interesting bits are in the first text/plain multipart part = None try: part = msg.get_payload(0) except IndexError: pass if not part: print 'out 3' return [] addrs = {} for line in Iterators.body_line_iterator(part): mo = acre.match(line) if mo: addrs[mo.group('addr')] = 1 return addrs.keys()
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Sina.py
Sina.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Contains all the common functionality for msg bounce scanning API. This module can also be used as the basis for a bounce detection testing framework. When run as a script, it expects two arguments, the listname and the filename containing the bounce message. """ import sys # If a bounce detector returns Stop, that means to just discard the message. # An example is warning messages for temporary delivery problems. These # shouldn't trigger a bounce notification, but we also don't want to send them # on to the list administrator. Stop = object() BOUNCE_PIPELINE = [ 'DSN', 'Qmail', 'Postfix', 'Yahoo', 'Caiwireless', 'Exchange', 'Exim', 'Netscape', 'Compuserve', 'Microsoft', 'GroupWise', 'SMTP32', 'SimpleMatch', 'SimpleWarning', 'Yale', 'LLNL', ] # msg must be a mimetools.Message def ScanMessages(mlist, msg): for module in BOUNCE_PIPELINE: modname = 'mailman.Bouncers.' + module __import__(modname) addrs = sys.modules[modname].process(msg) if addrs: # Return addrs even if it is Stop. BounceRunner needs this info. return addrs return []
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/BouncerAPI.py
BouncerAPI.py
# Copyright (C) 2000-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Yale's mail server is pretty dumb. Its reports include the end user's name, but not the full domain. I think we can usually guess it right anyway. This is completely based on examination of the corpse, and is subject to failure whenever Yale even slightly changes their MTA. :( """ import re from cStringIO import StringIO from email.Utils import getaddresses scre = re.compile(r'Message not delivered to the following', re.IGNORECASE) ecre = re.compile(r'Error Detail', re.IGNORECASE) acre = re.compile(r'\s+(?P<addr>\S+)\s+') def process(msg): if msg.is_multipart(): return None try: whofrom = getaddresses([msg.get('from', '')])[0][1] if not whofrom: return None username, domain = whofrom.split('@', 1) except (IndexError, ValueError): return None if username.lower() <> 'mailer-daemon': return None parts = domain.split('.') parts.reverse() for part1, part2 in zip(parts, ('edu', 'yale')): if part1 <> part2: return None # Okay, we've established that the bounce came from the mailer-daemon at # yale.edu. Let's look for a name, and then guess the relevant domains. names = {} body = StringIO(msg.get_payload()) state = 0 # simple state machine # 0 == init # 1 == intro found while 1: line = body.readline() if not line: break if state == 0 and scre.search(line): state = 1 elif state == 1 and ecre.search(line): break elif state == 1: mo = acre.search(line) if mo: names[mo.group('addr')] = 1 # Now we have a bunch of names, these are either @yale.edu or # @cs.yale.edu. Add them both. addrs = [] for name in names.keys(): addrs.append(name + '@yale.edu') addrs.append(name + '@cs.yale.edu') return addrs
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Yale.py
Yale.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Parse bounce messages generated by qmail. Qmail actually has a standard, called QSBMF (qmail-send bounce message format), as described in http://cr.yp.to/proto/qsbmf.txt This module should be conformant. """ import re import email.Iterators # Other (non-standard?) intros have been observed in the wild. introtags = [ 'Hi. This is the', "We're sorry. There's a problem", 'Check your send e-mail address.', 'This is the mail delivery agent at', 'Unfortunately, your mail was not delivered' ] acre = re.compile(r'<(?P<addr>[^>]*)>:') def process(msg): addrs = [] # simple state machine # 0 = nothing seen yet # 1 = intro paragraph seen # 2 = recip paragraphs seen state = 0 for line in email.Iterators.body_line_iterator(msg): line = line.strip() if state == 0: for introtag in introtags: if line.startswith(introtag): state = 1 break elif state == 1 and not line: # Looking for the end of the intro paragraph state = 2 elif state == 2: if line.startswith('-'): # We're looking at the break paragraph, so we're done break # At this point we know we must be looking at a recipient # paragraph mo = acre.match(line) if mo: addrs.append(mo.group('addr')) # Otherwise, it must be a continuation line, so just ignore it # Not looking at anything in particular return addrs
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Qmail.py
Qmail.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Parse RFC 3464 (i.e. DSN) bounce formats. RFC 3464 obsoletes 1894 which was the old DSN standard. This module has not been audited for differences between the two. """ from cStringIO import StringIO from email.Iterators import typed_subpart_iterator from email.Utils import parseaddr from mailman.Bouncers.BouncerAPI import Stop def check(msg): # Iterate over each message/delivery-status subpart addrs = [] for part in typed_subpart_iterator(msg, 'message', 'delivery-status'): if not part.is_multipart(): # Huh? continue # Each message/delivery-status contains a list of Message objects # which are the header blocks. Iterate over those too. for msgblock in part.get_payload(): # We try to dig out the Original-Recipient (which is optional) and # Final-Recipient (which is mandatory, but may not exactly match # an address on our list). Some MTA's also use X-Actual-Recipient # as a synonym for Original-Recipient, but some apparently use # that for other purposes :( # # Also grok out Action so we can do something with that too. action = msgblock.get('action', '').lower() # Some MTAs have been observed that put comments on the action. if action.startswith('delayed'): return Stop if not action.startswith('fail'): # Some non-permanent failure, so ignore this block continue params = [] foundp = False for header in ('original-recipient', 'final-recipient'): for k, v in msgblock.get_params([], header): if k.lower() == 'rfc822': foundp = True else: params.append(k) if foundp: # Note that params should already be unquoted. addrs.extend(params) break else: # MAS: This is a kludge, but SMTP-GATEWAY01.intra.home.dk # has a final-recipient with an angle-addr and no # address-type parameter at all. Non-compliant, but ... for param in params: if param.startswith('<') and param.endswith('>'): addrs.append(param[1:-1]) # Uniquify rtnaddrs = {} for a in addrs: if a is not None: realname, a = parseaddr(a) rtnaddrs[a] = True return rtnaddrs.keys() def process(msg): # A DSN has been seen wrapped with a "legal disclaimer" by an outgoing MTA # in a multipart/mixed outer part. if msg.is_multipart() and msg.get_content_subtype() == 'mixed': msg = msg.get_payload()[0] # The above will suffice if the original message 'parts' were wrapped with # the disclaimer added, but the original DSN can be wrapped as a # message/rfc822 part. We need to test that too. if msg.is_multipart() and msg.get_content_type() == 'message/rfc822': msg = msg.get_payload()[0] # The report-type parameter should be "delivery-status", but it seems that # some DSN generating MTAs don't include this on the Content-Type: header, # so let's relax the test a bit. if not msg.is_multipart() or msg.get_content_subtype() <> 'report': return None return check(msg)
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/DSN.py
DSN.py
# Copyright (C) 1998-2009 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. """Netscape Messaging Server bounce formats. I've seen at least one NMS server version 3.6 (envy.gmp.usyd.edu.au) bounce messages of this format. Bounces come in DSN MIME format, but don't include any -Recipient: headers. Gotta just parse the text :( NMS 4.1 (dfw-smtpin1.email.verio.net) seems even worse, but we'll try to decipher the format here too. """ import re from cStringIO import StringIO pcre = re.compile( r'This Message was undeliverable due to the following reason:', re.IGNORECASE) acre = re.compile( r'(?P<reply>please reply to)?.*<(?P<addr>[^>]*)>', re.IGNORECASE) def flatten(msg, leaves): # give us all the leaf (non-multipart) subparts if msg.is_multipart(): for part in msg.get_payload(): flatten(part, leaves) else: leaves.append(msg) def process(msg): # Sigh. Some show NMS 3.6's show # multipart/report; report-type=delivery-status # and some show # multipart/mixed; if not msg.is_multipart(): return None # We're looking for a text/plain subpart occuring before a # message/delivery-status subpart. plainmsg = None leaves = [] flatten(msg, leaves) for i, subpart in zip(range(len(leaves)-1), leaves): if subpart.get_content_type() == 'text/plain': plainmsg = subpart break if not plainmsg: return None # Total guesswork, based on captured examples... body = StringIO(plainmsg.get_payload()) addrs = [] while 1: line = body.readline() if not line: break mo = pcre.search(line) if mo: # We found a bounce section, but I have no idea what the official # format inside here is. :( We'll just search for <addr> # strings. while 1: line = body.readline() if not line: break mo = acre.search(line) if mo and not mo.group('reply'): addrs.append(mo.group('addr')) return addrs
zw.mail.incoming
/zw.mail.incoming-0.1.2.3.tar.gz/zw.mail.incoming-0.1.2.3/src/mailman/Bouncers/Netscape.py
Netscape.py
================== Zaehlwerk Fields ================== - Color field - Reference field - Rich text field
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/README.txt
README.txt
import os from setuptools import setup, find_packages def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() name = 'zw.schema' version = '0.3.0b2.1' setup(name=name, # Fill in project info below version=version, description="Additional schema fields for Zope 3", long_description=( read('README.txt') + '\n\n' + read('src', 'zw', 'schema', 'color', 'README.txt') + '\n\n' + read('src', 'zw', 'schema', 'reference', 'README.txt') + '\n\n' + read('src', 'zw', 'schema', 'richtext', 'README.txt') + '\n\n' + read('CHANGES.txt')), keywords='zope3', author='Gregor Giesen', author_email='giesen@zaehlwerk.net', url='https://launchpad.net/'+name, license='GPLv3', # Get more from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Framework :: Zope3', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', ], packages=find_packages('src'), package_dir = {'': 'src'}, namespace_packages=['zw'], include_package_data=True, zip_safe=False, extras_require = dict( test = ['zope.testing', ], ), install_requires = ['setuptools', 'zope.dottedname', 'zope.i18nmessageid', 'zope.interface', 'zope.schema', 'zope.app.intid', ], )
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/setup.py
setup.py
############################################################################## # # Copyright (c) 2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 tmpeggs = tempfile.mkdtemp() try: import pkg_resources except ImportError: ez = {} exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) import pkg_resources cmd = 'from setuptools.command.easy_install import main; main()' if sys.platform == 'win32': cmd = '"%s"' % cmd # work around spawn lamosity on windows ws = pkg_resources.working_set assert os.spawnle( os.P_WAIT, sys.executable, sys.executable, '-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout', dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse('setuptools')).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout') import zc.buildout.buildout zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap']) shutil.rmtree(tmpeggs)
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/bootstrap.py
bootstrap.py
# HIC FASCIS SPATIUM NOMINALIS EST. try: import pkg_resources pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/__init__.py
__init__.py
# HIC FASCIS PYTHONIS EST.
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import zope.i18nmessageid MessageFactory = zope.i18nmessageid.MessageFactory('zw.schema')
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/i18n.py
i18n.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import zope.schema import zope.schema.interfaces import zope.interface from zw.schema.richtext.interfaces import IRichText class RichText(zope.schema.Text): """Field describing a rich text field. """ zope.interface.implements(IRichText) def _validate(self, value): super(RichText, self)._validate(value)
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/richtext/field.py
field.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import zope.schema import zope.schema.interfaces class IRichText(zope.schema.interfaces.IField): """A rich text field. """
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/richtext/interfaces.py
interfaces.py
=============== Rich text Field =============== The text contained in the field describes a rich field in HTML format. Let's first generate a such a field: >>> from zw.schema.richtext import RichText >>> richtext = RichText()
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/richtext/README.txt
README.txt
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ from zw.schema.richtext.field import RichText
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/richtext/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import unittest from zope.testing import doctest from zope.testing.doctestunit import DocFileSuite def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/richtext/tests.py
tests.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import re import zope.schema import zope.schema.interfaces import zope.interface from zw.schema.color.interfaces import IColor, InvalidColor _iscolor = re.compile( r"^[a-fA-F0-9]{6}$" ).match class Color(zope.schema.Field): """Field describing a color: RRGGBB Hex format """ _type = str zope.interface.implements(IColor, zope.schema.interfaces.IFromUnicode) def _validate(self, value): super(Color, self)._validate(value) if _iscolor(value) is None: raise InvalidColor(value) def fromUnicode(self, u): """ """ v = str(u) self.validate(v) return v
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/color/field.py
field.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import zope.schema import zope.schema.interfaces class InvalidColor(zope.schema.interfaces.InvalidValue): __doc__ = _("""The specified string is no color.""") class IColor(zope.schema.interfaces.IField): """A color field. """
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/color/interfaces.py
interfaces.py
=========== Color Field =========== The string contained in the field describes a RGB color in hexdecimal format. Let's first generate a color field: >>> from zw.schema.color import Color >>> color = Color() Make sure the colors validate: >>> color.validate('aa00cc') >>> color.validate('00aa000') Traceback (most recent call last): ... InvalidColor: 00aa000
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/color/README.txt
README.txt
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ from zw.schema.color.field import Color
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/color/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import unittest from zope.testing import doctest from zope.testing.doctestunit import DocFileSuite def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/color/tests.py
tests.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import sys import zope.schema import zope.schema.interfaces import zope.component import zope.interface from zope.interface.interfaces import IInterface from zope.dottedname.resolve import resolve from zope.app.intid.interfaces import IIntIds from zw.schema.reference.interfaces import IReference class Reference(zope.schema.Field): """A field to an persistent object referencable by IntId. """ zope.interface.implements(IReference) _schemata = None def __init__(self, *args, **kw): schemata = kw.pop('schemata', None) if type(schemata) not in (tuple, list,): schemata = (schemata,) schema_list = [] for schema in schemata: if IInterface.providedBy(schema): schema_list.append(schema) elif isinstance(schema, str): # have dotted names #module = kw.get('module', sys._getframe(1).f_globals['__name__']) raise NotImplementedError schema_list.append(schema) elif schema is None: continue else: raise zope.schema.interfaces.WrongType if schema_list: self._schemata = tuple(schema_list) super(Reference, self).__init__(*args, **kw) def _validate(self, value): super(Reference, self)._validate(value) if self._schemata is not None: schema_provided = False for iface in self._schemata: if iface.providedBy(value): schema_provided = True if not schema_provided: raise zope.schema.interfaces.SchemaNotProvided intids = zope.component.getUtility(IIntIds, context=value) intids.getId(value) def get(self, object): id = super(Reference, self).get(object) intids = zope.component.getUtility(IIntIds, context=object) return intids.queryObject(id) def set(self, object, value): intids = zope.component.getUtility(IIntIds, context=object) id = intids.getId(value) super(Reference, self).set(object, id)
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/reference/field.py
field.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.schema.i18n import MessageFactory as _ import zope.schema import zope.schema.interfaces class IReference(zope.schema.interfaces.IField): """A field to an persitent object referencable by IntId. """
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/reference/interfaces.py
interfaces.py
=============== Reference Field ===============
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/reference/README.txt
README.txt
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ from zw.schema.reference.field import Reference
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/reference/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import unittest from zope.testing import doctest from zope.testing.doctestunit import DocFileSuite def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
zw.schema
/zw.schema-0.3.0b2.1.tar.gz/zw.schema-0.3.0b2.1/src/zw/schema/reference/tests.py
tests.py
=================== Zaehlwerk Widgets =================== Some widgets for the z3c.form framework. - Color widget - Email widget - Lines widget - TinyMCE widget
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/README.txt
README.txt
import os, sys, urllib, urllib2 from zipfile import ZipFile from HTMLParser import HTMLParser from setuptools import setup, find_packages def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() name = 'zw.widget' version = '0.1.6.2' extpaths = [] tinymce_version = '3.2.1.1' tinymce_src_name = 'tinymce_%s.zip' % tinymce_version.replace('.', '_') tinymce_base_url = 'http://downloads.sourceforge.net/tinymce' tinymce_dest = os.path.join(os.path.dirname(__file__), 'src', 'zw', 'widget', 'tiny', 'tiny_mce') tinymce_lang_src_name = 'tinymce_lang_pack.zip' tinymce_lang_base_url = 'http://services.moxiecode.com/i18n/' tinymce_lang_post_url = tinymce_lang_base_url+'download.aspx' params = dict(format='zip', product='tinymce') class TinyMCELangParser(HTMLParser): params = {} def handle_startendtag(self, tag, attrs): attrs = dict(attrs) if tag == 'input' and attrs.get('type',None) == 'checkbox' and \ 'name' in attrs and 'value' in attrs: self.params[attrs['name']] = attrs['value'] # Download the TinyMCE code if not os.path.exists(tinymce_src_name): if not os.path.exists(tinymce_src_name): f = open(tinymce_src_name, 'w') f.write(urllib2.urlopen( tinymce_base_url+'/'+tinymce_src_name).read()) f.close() zfile = ZipFile(tinymce_src_name, 'r') prefix = 'tinymce/jscripts/tiny_mce/' lprefix = len(prefix)-1 for zname in sorted(zfile.namelist()): assert zname.startswith('tinymce/') if zname.startswith(prefix): dname = tinymce_dest + zname[lprefix:] if dname[-1:] == '/': os.makedirs(dname) else: f = open(dname, 'w') f.write(zfile.read(zname)) f.close() zfile.close() # Download new language packs if not os.path.exists(tinymce_lang_src_name): parser = TinyMCELangParser() parser.feed(urllib2.urlopen( tinymce_lang_base_url ).read()) params.update(parser.params) fi = urllib2.urlopen( tinymce_lang_post_url, urllib.urlencode(params) ) fo = open(tinymce_lang_src_name, 'w') fo.write( fi.read() ) fo.close() fi.close() zfile = ZipFile(tinymce_lang_src_name, 'r') for zname in sorted(zfile.namelist()): dname = os.path.join(tinymce_dest, zname) if dname[-1:] == '/': os.makedirs(dname) else: f = open(dname, 'w') f.write(zfile.read(zname)) f.close() zfile.close() # Add files for packaging lbase = len(os.path.dirname(tinymce_dest))+1 for path, dirs, files in os.walk(tinymce_dest): prefix = path[lbase:] for file in files: extpaths.append(os.path.join(prefix, file)) setup(name=name, # Fill in project info below version=version, description="Additional widgets for z3c.form", long_description=( read('README.txt') + \ '\n\n' + read('src', 'zw', 'widget', 'color', 'README.txt') + \ '\n\n' + read('src', 'zw', 'widget', 'email', 'README.txt') + \ '\n\n' + read('src', 'zw', 'widget', 'lines', 'README.txt') + \ '\n\n' + read('src', 'zw', 'widget', 'tiny', 'README.txt') + \ '\n\n' + read('CHANGES.txt')), keywords='zope3', author='Gregor Giesen', author_email='giesen@zaehlwerk.net', url='https://launchpad.net/'+name, license='GPLv3', # Get more from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', 'Framework :: Zope3', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', ], packages=find_packages('src'), package_dir = {'': 'src'}, namespace_packages=['zw'], include_package_data=True, package_data = {'zw.widget.tiny': extpaths}, zip_safe=False, extras_require = dict( test = [ 'zope.testing', 'zope.app.testing', 'zope.app.zcmlfiles', 'zope.testbrowser', 'z3c.testsetup', ], ), install_requires = ['setuptools', 'zope.i18nmessageid', 'zope.interface', 'zope.schema', 'z3c.form', 'z3c.schema', 'zw.schema', 'zc.resourcelibrary', ], )
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/setup.py
setup.py
############################################################################## # # Copyright (c) 2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id$ """ import os, shutil, sys, tempfile, urllib2 tmpeggs = tempfile.mkdtemp() try: import pkg_resources except ImportError: ez = {} exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) import pkg_resources cmd = 'from setuptools.command.easy_install import main; main()' if sys.platform == 'win32': cmd = '"%s"' % cmd # work around spawn lamosity on windows ws = pkg_resources.working_set assert os.spawnle( os.P_WAIT, sys.executable, sys.executable, '-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout', dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse('setuptools')).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout') import zc.buildout.buildout zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap']) shutil.rmtree(tmpeggs)
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/bootstrap.py
bootstrap.py
# HIC FASCIS SPATIUM NOMINALIS EST. try: import pkg_resources pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/__init__.py
__init__.py
# HIC FASCIS PYTHONIS EST.
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import zope.i18nmessageid MessageFactory = zope.i18nmessageid.MessageFactory('zope')
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/i18n.py
i18n.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ from z3c.form.interfaces import ITextWidget class IColorWidget(ITextWidget): """A color widget. """
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/color/interfaces.py
interfaces.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ from zope.component import adapter, adapts from zope.interface import implementsOnly, implementer from z3c.form.browser import widget from z3c.form.interfaces import IFieldWidget, IFormLayer from z3c.form.widget import Widget, FieldWidget from zw.schema.color.interfaces import IColor from zw.widget.color.interfaces import IColorWidget class ColorWidget(widget.HTMLTextInputWidget, Widget): """Lines widget. """ implementsOnly(IColorWidget) klass = u'color-widget' value = u'' def update(self): super(ColorWidget, self).update() widget.addFieldClass(self) @adapter(IColor, IFormLayer) @implementer(IFieldWidget) def ColorFieldWidget(field, request): """IFieldWidget factory for ColorWidget. """ return FieldWidget(field, ColorWidget(request))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/color/widget.py
widget.py
=========== ColorWidget =========== The widget can render an input field with color preview:: >>> from zope.interface.verify import verifyClass >>> from z3c.form.interfaces import IWidget >>> from zw.widget.color.widget import ColorWidget The ColorWidget is a widget:: >>> verifyClass(IWidget, ColorWidget) True The widget can render a input field only by adapting a request:: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = ColorWidget(request) Such a field provides IWidget:: >>> IWidget.providedBy(widget) True We also need to register the template for at least the widget and request:: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import zw.widget.color >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(zw.widget.color.__file__), ... 'color_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML:: >>> print widget.render() <input type="text" class="color-widget" value="" /> Adding some more attributes to the widget will make it display more:: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'value' >>> print widget.render() <span id="" class="color-widget color-sample" style="background-color: #value;"> </span> <input type="text" id="id" name="name" class="color-widget" value="value" />
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/color/README.txt
README.txt
# HIC FASCIS PYTHONIS EST.
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/color/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import doctest import unittest from zope.testing.doctestunit import DocFileSuite from z3c.form import testing def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', setUp=testing.setUp, tearDown=testing.tearDown, optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, ), ))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/color/tests.py
tests.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ from zope import schema from z3c.form.interfaces import IWidget class IEmailWidget(IWidget): """An email widget. """ obscured = schema.Bool( title = _( u'label-zw.widget.email.obscured', u"Obscured" ), description = _( u'help-zw.widget.email.obscured', u"If true the address will be obscured " u"to protect from spam bots." ), default = True )
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/email/interfaces.py
interfaces.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ from zope.component import adapter, adapts from zope.interface import implementsOnly, implementer from zope.app.security.interfaces import IUnauthenticatedPrincipal from z3c.form.browser import widget from z3c.form.interfaces import IFieldWidget, IFormLayer from z3c.form.widget import Widget, FieldWidget from z3c.schema.email.interfaces import IRFC822MailAddress from zw.widget.email.interfaces import IEmailWidget class EmailWidget(widget.HTMLTextInputWidget, Widget): """Email widget. """ implementsOnly(IEmailWidget) klass = u'email-widget' value = u'' obscured = False def update(self): # Obscure email if unauthenticated. self.obscured = IUnauthenticatedPrincipal.providedBy( self.request.principal) super(EmailWidget, self).update() widget.addFieldClass(self) @adapter(IRFC822MailAddress, IFormLayer) @implementer(IFieldWidget) def EmailFieldWidget(field, request): """IFieldWidget factory for EmailWidget. """ return FieldWidget(field, EmailWidget(request))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/email/widget.py
widget.py
=========== EmailWidget =========== The widget can render an ordinary input field:: >>> from zope.interface.verify import verifyClass >>> from z3c.form.interfaces import IWidget, INPUT_MODE, DISPLAY_MODE >>> from zw.widget.email.widget import EmailWidget The EmailWidget is a widget:: >>> verifyClass(IWidget, EmailWidget) True The widget can render a input field only by adapting a request:: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = EmailWidget(request) Such a field provides IWidget:: >>> IWidget.providedBy(widget) True We also need to register the template for at least the widget and request:: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import zw.widget.email >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(zw.widget.email.__file__), ... 'email_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML:: >>> print widget.render() <input type="text" class="email-widget" value="" /> Adding some more attributes to the widget will make it display more:: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'name@domain.tld' >>> print widget.render() <input type="text" id="id" name="name" class="email-widget" value="name@domain.tld" /> More interesting is to the display view:: >>> widget.mode = DISPLAY_MODE >>> template = os.path.join(os.path.dirname(zw.widget.email.__file__), ... 'email_display.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='display') >>> print widget.render() <span id="id" class="email-widget"> <a href="mailto:name@domain.tld"> name@domain.tld </a> </span> But if we are not authenticated it should be obscured: >>> widget.obscured = True >>> print widget.render() <span id="id" class="email-widget"> name@domain.tld </span>
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/email/README.txt
README.txt
# HIC FASCIS PYTHONIS EST.
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/email/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import doctest import unittest from zope.testing.doctestunit import DocFileSuite from z3c.form import testing def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', setUp=testing.setUp, tearDown=testing.tearDown, optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, ), ))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/email/tests.py
tests.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ import zope.schema from z3c.form.interfaces import ITextAreaWidget class ITinyWidget(ITextAreaWidget): """A WYSIWYG input widget for editing html which uses tinymce editor. """ tiny_js = zope.schema.Text( title = u'TinyMCE init ECMAScript code', description = u'This ECMAScript code initialize the TinyMCE widget ' \ u'to the textarea.', required = False )
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/tiny/interfaces.py
interfaces.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ import zope.schema.interfaces from zope.component import adapter from zope.interface import implementsOnly, implementer from z3c.form.browser.textarea import TextAreaWidget from z3c.form.interfaces import IFormLayer, IFieldWidget from z3c.form.widget import FieldWidget from zw.schema.richtext.interfaces import IRichText from zw.widget.tiny.interfaces import ITinyWidget try: from zc import resourcelibrary haveResourceLibrary = True except ImportError: haveResourceLibrary = False OPT_PREFIX = "mce_" OPT_PREFIX_LEN = len(OPT_PREFIX) MCE_LANGS=[] import glob import os # initialize the language files for langFile in glob.glob( os.path.join(os.path.dirname(__file__), 'tiny_mace', 'langs') + '/??.js'): MCE_LANGS.append(os.path.basename(langFile)[:2]) class TinyWidget(TextAreaWidget): """TinyMCE widget implementation. """ implementsOnly(ITinyWidget) klass = u'tiny-widget' value = u'' tiny_js = u"" rows = 10 cols = 60 mce_theme = "advanced" mce_theme_advanced_buttons1 = "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink" mce_theme_advanced_buttons2 = "" mce_theme_advanced_buttons3 = "" mce_theme_advanced_toolbar_location = "top" mce_theme_advanced_toolbar_align = "left" mce_theme_advanced_statusbar_location = "bottom" mce_extended_valid_elements = "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]" def update(self): super(TinyWidget, self).update() if haveResourceLibrary: resourcelibrary.need('tiny_mce') mceOptions = [] for k in dir(self): if k.startswith(OPT_PREFIX): v = getattr(self, k, None) v = v==True and 'true' or v==False and 'false' or v if v in ['true','false']: mceOptions.append('%s : %s' % (k[OPT_PREFIX_LEN:],v)) elif v is not None: mceOptions.append('%s : "%s"' % (k[OPT_PREFIX_LEN:],v)) mceOptions = ', '.join(mceOptions) if mceOptions: mceOptions += ', ' if self.request.locale.id.language in MCE_LANGS: mceOptions += ('language : "%s", ' % \ self.request.locale.id.language) self.tiny_js = u""" tinyMCE.init({ mode : "exact", %(options)s elements : "%(id)s" } ); """ % { "id": self.id, "options": mceOptions } @adapter(IRichText, IFormLayer) @implementer(IFieldWidget) def TinyFieldWidget(field, request): """IFieldWidget factory for TinyWidget. """ return FieldWidget(field, TinyWidget(request))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/tiny/widget.py
widget.py
========== TinyWidget ========== The widget can render a HTML text input field based on the TinyMCE JavaScript Content Editor from Moxicode Systems ..http://tinymce.moxiecode.com >>> from zope.interface.verify import verifyClass >>> from zope.app.form.interfaces import IInputWidget >>> from z3c.form.interfaces import IWidget >>> from zw.widget.tiny.widget import TinyWidget The TinyWidget is a widget: >>> verifyClass(IWidget, TinyWidget) True The widget can render a textarea field only by adapteing a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = TinyWidget(request) Such a field provides IWidget: >>> IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import zw.widget.tiny >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(zw.widget.tiny.__file__), ... 'tiny_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML: >>> print widget.render() <textarea class="tiny-widget" cols="60" rows="10"></textarea> Adding some more attributes to the widget will make it display more: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'value' >>> print widget.render() <textarea id="id" name="name" class="tiny-widget" cols="60" rows="10">value</textarea> TODO: Testing for ECMAScript code...
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/tiny/README.txt
README.txt
# HIC FASCIS PYTHONIS EST.
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/tiny/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import doctest import unittest from zope.testing.doctestunit import DocFileSuite from z3c.form import testing def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', setUp=testing.setUp, tearDown=testing.tearDown, optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, ), ))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/tiny/tests.py
tests.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ from z3c.form.interfaces import IWidget class ILinesWidget(IWidget): """A lines widget. """
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/interfaces.py
interfaces.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ import zope.schema.interfaces from zope.component import adapts from z3c.form.converter import BaseDataConverter from zw.widget.lines.interfaces import ILinesWidget class LinesDataConverter(BaseDataConverter): """A lines to list or tuple converter. """ adapts(zope.schema.interfaces.IList, ILinesWidget) def toFieldValue(self, value): """See z3c.form.interfaces.IDataConverter. """ if value is None or value == u'': return self.field.missing_value if '\r\n' in value: lines = value.split(u'\r\n') else: lines = value.split(u'\n') if hasattr(self.field.value_type, 'fromUnicode'): return [ self.field.value_type.fromUnicode(line) for line in lines ] return lines def toWidgetValue(self, value): """See z3c.form.interfaces.IDataConverter. """ if value is self.field.missing_value: return u'' return u'\n'.join( [ unicode(item) for item in value ] )
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/converter.py
converter.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' from zw.widget.i18n import MessageFactory as _ import zope.schema.interfaces from zope.component import adapter from zope.interface import implementsOnly, implementer from z3c.form.browser.widget import HTMLTextAreaWidget, addFieldClass from z3c.form.interfaces import IFormLayer, IFieldWidget from z3c.form.widget import Widget, FieldWidget from zw.widget.lines.interfaces import ILinesWidget class LinesWidget(HTMLTextAreaWidget, Widget): """Lines widget. """ implementsOnly(ILinesWidget) klass = u'lines-widget' value = u'' def update(self): super(LinesWidget, self).update() addFieldClass(self) @adapter(zope.schema.interfaces.IList, IFormLayer) @implementer(IFieldWidget) def LinesFieldWidget(field, request): """IFieldWidget factory for LinesWidget. """ return FieldWidget(field, LinesWidget(request))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/widget.py
widget.py
=========== LinesWidget =========== The widget can render a HTML text input field, which collects list items by line. >>> from zope.interface.verify import verifyClass >>> from z3c.form.interfaces import IWidget >>> from zw.widget.lines.widget import LinesWidget The LinesWidget is a widget: >>> verifyClass(IWidget, LinesWidget) True The widget can render a textarea field only by adapteing a request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> widget = LinesWidget(request) Such a field provides IWidget: >>> IWidget.providedBy(widget) True We also need to register the template for at least the widget and request: >>> import os.path >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.pagetemplate.interfaces import IPageTemplate >>> import zw.widget.lines >>> import z3c.form.widget >>> template = os.path.join(os.path.dirname(zw.widget.lines.__file__), ... 'lines_input.pt') >>> factory = z3c.form.widget.WidgetTemplateFactory(template) >>> zope.component.provideAdapter(factory, ... (zope.interface.Interface, IDefaultBrowserLayer, None, None, None), ... IPageTemplate, name='input') If we render the widget we get the HTML: >>> print widget.render() <textarea class="lines-widget"></textarea> Adding some more attributes to the widget will make it display more: >>> widget.id = 'id' >>> widget.name = 'name' >>> widget.value = u'value' >>> print widget.render() <textarea id="id" name="name" class="lines-widget">value</textarea>
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/README.txt
README.txt
# HIC FASCIS PYTHONIS EST.
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/__init__.py
__init__.py
#-*- coding: utf-8 -*- ############################################################################# # # # Copyright (c) 2007-2008 Gregor Giesen <giesen@zaehlwerk.net> # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# """ $Id$ """ __docformat__ = 'reStructuredText' import doctest import unittest from zope.testing.doctestunit import DocFileSuite from z3c.form import testing def test_suite(): return unittest.TestSuite(( DocFileSuite( 'README.txt', setUp=testing.setUp, tearDown=testing.tearDown, optionflags = doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, ), ))
zw.widget
/zw.widget-0.1.6.2.tar.gz/zw.widget-0.1.6.2/src/zw/widget/lines/tests.py
tests.py
# ZWare API The zwave controller was developed for z-wave 700 series. Is a client that works with Z/IP Gateway SDK and Z-Ware SDK. ### Example ```zw = ZWareApi() zwC = zwClient(zw, 'host', 'user', 'pass') zwC.login() print (zwC.get_node_list()) ```
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/README.md
README.md
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="zware_api", version="0.0.25", author="Alfonso Brown", author_email="alfonso.gonzalez@casai.com", description="A python package to control Z-Wave devices in a ZWare network.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/casai-org/zwave_controller", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "Operating System :: OS Independent", ], python_requires='>=3.6', )
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/setup.py
setup.py
import urllib3 import zware_api.interfaces as interfaces from .const import DEVICE_DATABASE COMMAND_CLASSES = { "76": interfaces.zwLockLogging, "78": interfaces.zwScheduleEntry, "98": interfaces.zwLock, "99": interfaces.zwUserCode, "113": interfaces.zwAlarm, "128": interfaces.zwBattery, } class zwClient(object): """Representation of a Z-Wave network client.""" CMD_ADD_NODE = 2 CMD_DELETE_NODE = 3 def __init__(self, zware_object, host, user, password): """Initialize a z-wave client.""" urllib3.disable_warnings() self.zware = zware_object self.ipAddress = host self.username = user self.password = password self.nodes = list() def login(self): """Connect to the server""" board_ip = 'https://' + self.ipAddress + '/' r = self.zware.zw_init(board_ip, self.username, self.password) v = r.findall('./version')[0] return v.get('app_major') + '.' + v.get('app_minor') def get_node_list(self, active=False): """Get nodes in the z-wave network.""" if active: nodes_list = list() nodes = self.zware.zw_api('zwnet_get_node_list') nodes = nodes.findall('./zwnet/zwnode') for node in nodes: node_obj = zwNode(self.zware, node.get('id'), node.get('property'), node.get('vid'), node.get('pid'), node.get('type'), node.get('category'), node.get('alive'), node.get('sec')) nodes_list.append(node_obj) self.nodes = nodes_list return self.nodes def add_node(self): """Activate adding mode in a Z-Wave network.""" self.zware.zw_add_remove(self.CMD_ADD_NODE) self.zware.zw_net_comp(self.CMD_ADD_NODE) def remove_node(self): """Activate exclusion mode in a Z-Wave network.""" self.zware.zw_add_remove(self.CMD_DELETE_NODE) self.zware.zw_net_comp(self.CMD_DELETE_NODE) def cancel_command(self): """Cancel the last sent Z-Wave command.""" self.zware.zw_abort() class zwNode: """Representation of a Z-Wave Node.""" def __init__(self, zware, id, property, manufacturer_id, product_id, product_type, device_category, alive_state, is_secure): """Initialize a z-wave node.""" self.zware = zware # Properties of a z-wave node. self.id = id self.property = property self.manufacturer_id = manufacturer_id self.product_id = product_id self.product_type = product_type self.device_category = device_category self.alive_state = alive_state self.is_secure = (int(is_secure) == 1) self.endpoints = list() self.name = None self.location = None def get_name_and_location(self, active=False): """Get the current name and location of a node.""" if active: endpoints = self.zware.zw_api('zwnode_get_ep_list', 'noded=' + self.id) endpoints = endpoints.findall('./zwnode/zwep') self.name = endpoints[0].get('name', '').replace("%20", " ") self.location = endpoints[0].get('loc').replace("%20", " ") return self.name, self.location def set_node_name_and_location(self, name, location): """Set the name and location of a node.""" if len(self.endpoints) == 0: self.get_endpoints(active=True) self.zware.zw_nameloc(self.endpoints[0].id, name, location) self.name = name self.location = location def get_readable_manufacturer_model(self): """Return a tupple with human-readable device manufacturer and model""" return (DEVICE_DATABASE.get(self.manufacturer_id, {}).get("name"), DEVICE_DATABASE.get(self.manufacturer_id, {}).get( "product",{}).get(self.product_id, {}).get(self.product_type)) def send_nif(self): """Send a node information frame to the node.""" self.zware.zw_api('zwnet_send_nif', 'noded=' + self.id) self.zware.zw_net_wait() def update(self): """Update the node status in the zwave network.""" self.zware.zw_api('zwnode_update', 'noded=' + self.id) self.zware.zw_net_wait() def get_endpoints(self, active=False): """Get endpoints in a z-wave node.""" if active: ep_list = list() endpoints = self.zware.zw_api('zwnode_get_ep_list', 'noded=' + self.id) endpoints = endpoints.findall('./zwnode/zwep') for ep in endpoints: ep_obj = zwEndpoint(self.zware, ep.get('desc'), ep.get('generic'), ep.get('specific'), ep.get('name'), ep.get('loc'), ep.get('zwplus_ver'), ep.get('role_type'), ep.get('node_type'), ep.get('instr_icon'), ep.get('usr_icon')) ep_list.append(ep_obj) self.endpoints = ep_list return self.endpoints class zwEndpoint: """Representation of a Z-Wave Endpoint.""" def __init__(self, zware, id, generic, specific, name, location, version, role_type, node_type, instr_icon, user_icon): """Initialize a z-wave endpoint.""" self.zware = zware # Properties of a z-wave endpoint. self.id = id self.generic = generic self.specific = specific self.name = name self.location = location self.zw_plus_version = version self.role_type = role_type self.node_type = node_type self.installer_icon = instr_icon self.user_icon = user_icon self.interfaces = list() def get_interfaces(self, active=False): """Get all the interfaces of an endpoint.""" if active: if_list = list() itfs = self.zware.zw_api('zwep_get_if_list', 'epd=' + self.id) itfs = itfs.findall('./zwep/zwif') for itf in itfs: type_id = itf.get('id') if_obj = COMMAND_CLASSES.get(type_id, interfaces.zwInterface)(self.zware, itf.get('desc'), type_id, itf.get('name'), itf.get('ver'), itf.get('real_ver'), itf.get('sec'), itf.get('unsec')) if_list.append(if_obj) self.interfaces = if_list return self.interfaces
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/objects.py
objects.py
DEVICE_DATABASE = { "297": { "name": "ASSA ABLOY", "product": { "0": { "1": "Yale Touchscreen Lever (YRL220)", "2": "Yale Touchscreen Deadbolt (YRD220)", "4": "Yale Push Button Deadbolt (YRD210)", "6": "Yale Key Free Touchscreen Deadbolt (YRD240)", }, "521": { "2": "Yale Key Free Touchscreen Deadbolt (YRD240)", "4": "Yale Push Button Deadbolt (YRD210)" }, "1033": { "3": "Yale Push Button Lever Lock (YRL210)", }, "1536": { "32770": "Yale Touchscreen Deadbolt (YRD226/YRD246/YRD446)", "32772": "Yale Push Button Deadbolt (YRD216)", }, "2048": { "2": "Yale Touchscreen Deadbolt (YRD120)", "3": "Yale Push Button Lever Lock (YRL210)", "4": "Yale Push Button Deadbolt (YRD110)", }, "4096": { "32770": "Yale Key Free Touchscreen Deadbolt (YRD446)", }, "43520": { "2": "Yale Touchscreen Deadbolt (YRD220)", "4": "Yale Push Button Deadbolt (YRD210)", }, } } }
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/const.py
const.py
# Copyright 2014-2018 Silicon Laboratories Inc. # The licensor of this software is Silicon Laboratories Inc. Your use of this software is governed by the terms of Silicon Labs Z-Wave Development Kit License Agreement. A copy of the license is available at www.silabs.com. import requests import xml.etree.ElementTree as ET class ZWareApi: """The ZWare web API.""" zware_session = None zware_url = "" def zw_api(self, uri, parm=''): r = self.zware_session.post(self.zware_url + uri, data=parm, verify=False) assert r.status_code == 200, "Unexpected response from Z-Ware API: {}".format(r.status_code) try: x = ET.fromstring(r.text) except: return r.text e = x.find('./error') assert e is None, e.text return x """Network operations""" def zw_net_wait(self): while int(self.zw_api('zwnet_get_operation').find('./zwnet/operation').get('op')): pass def zw_net_comp(self, op): while op != int(self.zw_api('zwnet_get_operation').find('./zwnet/operation').get('prev_op')): pass def zw_net_op_sts(self, op): while op != int(self.zw_api('zwnet_get_operation').find('./zwnet/operation').get('op_sts')): pass def zw_net_get_grant_keys(self): grant_key = self.zw_api('zwnet_add_s2_get_req_keys').find('./zwnet/security').get('req_key') return grant_key def zw_net_add_s2_get_dsk(self): dsk = self.zw_api('zwnet_add_s2_get_dsk').find('./zwnet/security').get('dsk') return dsk def zw_net_set_grant_keys(self, grant_key): return self.zw_api('zwnet_add_s2_set_grant_keys', 'granted_keys=' + grant_key) def zw_net_provisioning_list_add(self, dsk, boot_mode, grant_keys, interval, device_name, device_location, application_version, sub_version, vendor, product_id, product_type, status, generic_class, specific_class, installer_icon, uuid_format, uuid): provisioning_list_string = 'dsk=' + dsk if device_name != "": provisioning_list_string = provisioning_list_string + '&name=' + device_name if device_location != "": provisioning_list_string = provisioning_list_string + '&loc=' + device_location if generic_class != "": provisioning_list_string = provisioning_list_string + '&ptype_generic=' + generic_class if specific_class != "": provisioning_list_string = provisioning_list_string + '&ptype_specific=' + specific_class if installer_icon != "": provisioning_list_string = provisioning_list_string + '&ptype_icon=' + installer_icon if vendor != "": provisioning_list_string = provisioning_list_string + '&pid_manufacturer_id=' + vendor if product_type != "": provisioning_list_string = provisioning_list_string + '&pid_product_type=' + product_type if product_id != "": provisioning_list_string = provisioning_list_string + '&pid_product_id=' + product_id if application_version != "": provisioning_list_string = provisioning_list_string + '&pid_app_version=' + application_version if sub_version != "": provisioning_list_string = provisioning_list_string + '&pid_app_sub_version=' + sub_version if interval != "": provisioning_list_string = provisioning_list_string + '&interval=' + interval if uuid_format != "": provisioning_list_string = provisioning_list_string + '&uuid_format=' + uuid_format if uuid != "": provisioning_list_string = provisioning_list_string + '&uuid_data=' + uuid if status != "": provisioning_list_string = provisioning_list_string + '&pl_status=' + status if grant_keys != "": provisioning_list_string = provisioning_list_string + '&grant_keys=' + grant_keys if boot_mode != "": provisioning_list_string = provisioning_list_string + '&boot_mode=' + boot_mode return self.zw_api('zwnet_provisioning_list_add', provisioning_list_string) def zw_net_provisioning_list_list_get(self): devices_info = self.zw_api('zwnet_provisioning_list_list_get').findall('./zwnet/pl_list/pl_device_info') return devices_info def zw_net_provisioning_list_remove(self, dsk): result = self.zw_api('zwnet_provisioning_list_remove', 'dsk=' + dsk) return result def zw_net_provisioning_list_remove_all(self): result = self.zw_api('zwnet_provisioning_list_remove_all') return result def zw_net_set_dsk(self, dsk): return self.zw_api('zwnet_add_s2_accept', 'accept=1&value=' + dsk) def zw_init(self, url='https://127.0.0.1/', user='test_user', pswd='test_password', get_version=True): self.zware_session = requests.session() self.zware_url = url self.zware_session.headers.update({'Content-Type': 'application/x-www-form-urlencoded'}) # apache requires this self.zw_api('register/login.php', 'usrname=' + user + '&passwd=' + pswd) self.zware_url += 'cgi/zcgi/networks//' if get_version: return self.zw_api('zw_version') else: return def zw_add_remove(self, cmd): return self.zw_api('zwnet_add', 'cmd=' + str(cmd)) def zw_abort(self): return self.zw_api('zwnet_abort', '') def zw_nameloc(self, epd, name, location): return self.zw_api('zwep_nameloc', 'cmd=1&epd=' + epd + '&name=' + name + '&loc=' + location) """ Interfaces """ def zwif_api(self, dev, ifd, cmd=1, arg=''): return self.zw_api('zwif_' + dev, 'cmd=' + str(cmd) + '&ifd=' + str(ifd) + arg) def zwif_api_ret(self, dev, ifd, cmd=1, arg=''): r = self.zwif_api(dev, ifd, cmd, arg) if cmd == 2 or cmd == 3: return r.find('./zwif/' + dev) return r def zwif_basic_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('basic', ifd, cmd, arg) def zwif_switch_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('switch', ifd, cmd, arg) def zwif_level_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('level', ifd, cmd, arg) def zwif_thermo_list_api(self, dev, ifd, cmd=1, arg=''): r = self.zwif_api_ret('thrmo_' + dev, ifd, cmd, arg) if cmd == 5 or cmd == 6: return r.find('./zwif/thrmo_' + dev + '_sup') return r def zwif_thermo_mode_api(self, ifd, cmd=1, arg=''): return self.zwif_thermo_list_api('md', ifd, cmd, arg) def zwif_thermo_state_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('thrmo_op_sta', ifd, cmd, arg) def zwif_thermo_setpoint_api(self, ifd, cmd=1, arg=''): return self.zwif_thermo_list_api('setp', ifd, cmd, arg) def zwif_thermo_fan_mode_api(self, ifd, cmd=1, arg=''): return self.zwif_thermo_list_api('fan_md', ifd, cmd, arg) def zwif_thermo_fan_state_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('thrmo_fan_sta', ifd, cmd, arg) def zwif_meter_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('meter', ifd, cmd, arg) def zwif_bsensor_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('bsensor', ifd, cmd, arg) def zwif_sensor_api(self, ifd, cmd=1, arg=''): return self.zwif_api_ret('sensor', ifd, cmd, arg) def zwif_av_api(self, ifd, cmd=1, arg=''): r = self.zwif_api('av', ifd, cmd, arg) if cmd == 2 or cmd == 3: return r.find('./zwif/av_caps') return r
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/zware.py
zware.py
from .objects import zwInterface import asyncio EVENTS = { "0": { "9": { "1": "Deadbolt jammed while locking", "2": "Deadbolt jammed while unlocking", }, "18": { "default": "Keypad Lock with user_id {}", }, "19": { "default": "Keypad Unlock with user_id {}", }, "21": { "1": "Manual Lock by Key Cylinder or Thumb-Turn", "2": "Manual Lock by Touch Function", "3": "Manual Lock by Inside Button", }, "22": { "1": "Manual Unlock Operation", }, "24": { "1": "RF Lock Operation", }, "25": { "1": "RF Unlock Operation", }, "27": { "1": "Auto re-lock cycle complete", }, "33": { "default": "Single user code deleted with user_id {}", }, "38": { "default": "Non access code entered with user_id {}", }, "96": { "default": "Daily Schedule has been set/erased for user_id {}" }, "97": { "default": "Daily Schedule has been enabled/disabled for user_id {}" }, "98": { "default": "Yearly Schedule has been set/erased for user_id {}" }, "99": { "default": "Yearly Schedule has been enabled/disabled for user_id {}" }, "100": { "default": "All Schedules have been set/erased for user_id {}" }, "101": { "default": "All Schedules have been enabled/disabled for user_id {}" }, "112": { "default": "New user code added with user_id {}", "0": "Master Code was changed at keypad", "251": "Master Code was changed over RF", }, "113": { "0": "Duplicate Master Code error", "default": "Duplicate Pin-Code error with user_id {}", }, "130": { "0": "Door Lock needs Time Set" }, "131": { "default": "Disabled user_id {} code was entered at the keypad" }, "132": { "default": "Valid user_id {} code was entered outside of schedule" }, "161": { "1": "Keypad attempts exceed limit", "2": "Front Escutcheon removed from main", "3": "Master Code attempts exceed limit", }, "167": { "default": "Low Battery Level {}", }, "168": { "default": "Critical Battery Level {}", } }, "6": { "0": "State idle", "1": "Manual Lock Operation", "2": "Manual Unlock Operation", "3": "RF Lock Operation", "4": "RF Unlock Operation", "5": "Keypad Lock Operation", "6": "Keypad Unlock Operation", "7": "Manual Not Fully Locked Operation", "8": "RF Not Fully Locked Operation", "9": "Auto Lock Locked Operation", "10": "Auto Lock Not Fully Operation", "11": "Lock Jammed", "12": "All user codes deleted", "13": "Single user code deleted", "14": "New user code added", "15": "New user code not added due to duplicate code", "16": "Keypad temporary disabled", "17": "Keypad busy", "18": "New Program code Entered - Unique code for lock configuration", "19": "Manually Enter user Access code exceeds code limit", "20": "Unlock By RF with invalid user code", "21": "Locked by RF with invalid user codes", "22": "Window/Door is open", "23": "Window/Door is closed", "24": "Window/door handle is open", "25": "Window/door handle is closed", "32": "Messaging User Code entered via keypad", "64": "Barrier performing Initialization process", "65": "Barrier operation (Open / Close) force has been exceeded.", "66": "Barrier motor has exceeded manufacturer’s operational time limit", "67": "Barrier operation has exceeded physical mechanical limits.", "68": "Barrier unable to perform requested operation due to UL requirements", "69": "Barrier Unattended operation has been disabled per UL requirements", "70": "Barrier failed to perform Requested operation, device malfunction", "71": "Barrier Vacation Mode", "72": "Barrier Safety Beam Obstacle", "73": "Barrier Sensor Not Detected / Supervisory Error", "74": "Barrier Sensor Low Battery Warning", "75": "Barrier detected short in Wall Station wires", "76": "Barrier associated with non-Z-wave remote control", "254": "Unknown Event" }, "8": { "1": "Door Lock needs Time Set", "10": "Low Battery", "11": "Critical Battery Level" } } class zwLock(zwInterface): """Representation of a Z-Wave Lock Command Class.""" CMD_OPEN_DOOR = 0 CMD_CLOSE_DOOR = 255 CMD_DLOCK_SETUP = 1 CMD_DLOCK_OP_ACTIVE_GET = 2 CMD_DLOCK_OP_PASSIVE_GET = 3 CMD_DLOCK_OP_SET = 4 CMD_DLOCK_CFG_ACTIVE_GET = 5 CMD_DLOCK_CFG_PASSIVE_GET = 6 def send_command(self, cmd, arg='', dev='dlck'): """Send a command to the Doorlock Command Class.""" super(self, zwLock).send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='dlck'): """Send a command to the Doorlock Command Class that returns data.""" r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_DLOCK_OP_ACTIVE_GET or cmd == self.CMD_DLOCK_OP_PASSIVE_GET: return r.find('./zwif/' + dev + '_op') elif cmd == self.CMD_DLOCK_CFG_ACTIVE_GET or cmd == self.CMD_DLOCK_CFG_PASSIVE_GET: return r.find('./zwif/' + dev + '_cfg') return r def get_status(self, active=False): """Get status from the Doorlock Command Class.""" cmd = self.CMD_DLOCK_OP_ACTIVE_GET if active else self.CMD_DLOCK_OP_PASSIVE_GET sts_lock_door = self.ret_command(cmd) self.status = (int(sts_lock_door.get('mode')) == self.CMD_OPEN_DOOR) return {'is_open': self.status} def lock(self): """Operate the Doorlock Command Class to lock.""" self.send_command(self.CMD_DLOCK_SETUP) # Select this Command Class. self.send_command(self.CMD_DLOCK_OP_SET, '&mode=' + str(self.CMD_CLOSE_DOOR)) def unlock(self, ifd): """Operate the Doorlock Command Class to unlock.""" self.send_command(self.CMD_DLOCK_SETUP) # Select this Command Class. self.send_command(self.CMD_DLOCK_OP_SET, '&mode=' + str(self.CMD_OPEN_DOOR)) class zwBattery(zwInterface): """Representation of a Z-Wave Battery Command Class.""" CMD_BATTERY_ACTIVE_GET = 2 CMD_BATTERY_PASSIVE_GET = 3 def send_command(self, cmd, arg='', dev='battery'): """Send a command to the Battery Command Class.""" super(self, zwBattery).send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='battery'): """Send a command to the Battery Command Class that returns data.""" return super(self, zwBattery).ret_command(cmd, arg=arg, dev=dev) def get_status(self, active=False): """Get the battery level of the lock.""" cmd = self.CMD_BATTERY_ACTIVE_GET if active else self.CMD_BATTERY_PASSIVE_GET status = self.ret_command(cmd) self.status = int(status.get('level')) return {'battery': self.status} class zwUserCode(zwInterface): """Representation of a Z-Wave User Code Command Class.""" CMD_USER_CODE_ACTIVE_GET = 1 CMD_USER_CODE_PASSIVE_GET = 2 CMD_USER_CODE_SET = 3 CMD_USER_CODE_USERS_ACTIVE_GET = 4 CMD_USER_CODE_USERS_PASSIVE_GET = 5 CMD_USER_CODE_MASTER_ACTIVE_GET = 11 CMD_USER_CODE_MASTER_PASSIVE_GET = 12 CMD_USER_CODE_MASTER_SET = 13 STATUS_UNOCCUPIED = 0 STATUS_OCCUPIED_ENABLED = 1 STATUS_OCCUPIED_DISABLED = 3 STATUS_NON_ACCESS_USER = 4 def send_command(self, cmd, arg='', dev='usrcod'): """Send a command to the User Code Command Class.""" super(self, zwUserCode).send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='usrcod'): """Send a command to the User Code Command Class that returns data.""" r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_USER_CODE_ACTIVE_GET or cmd == self.CMD_USER_CODE_PASSIVE_GET: return r.find('./zwif/' + dev) elif cmd == self.CMD_USER_CODE_USERS_ACTIVE_GET or cmd == self.CMD_USER_CODE_USERS_PASSIVE_GET: return r.find('./zwif/usrcod_sup') return r def get_master_code(self, active=False): """Get the master code. Only if the specific devices' User Code Command Class supports it.""" cmd = self.CMD_USER_CODE_MASTER_ACTIVE_GET if active else self.CMD_USER_CODE_MASTER_PASSIVE_GET status = self.ret_command(cmd) return {'master_code': status.get('master_code')} async def set_master_code(self, code, verify=True): """Set the master code. Only if the specific devices' User Code Command Class supports it.""" try: self.send_command(self.CMD_USER_CODE_MASTER_SET, arg='&master_code={}'.format(code)) except: return False if verify: timeout = 0 while self.ret_command(self.CMD_USER_CODE_MASTER_ACTIVE_GET).get('master_code') != str(code): if timeout >= 20: return False await asyncio.sleep(1) timeout += 1 return True async def set_codes(self, user_ids: list, status: list, codes=None, verify=True): """Set a list of code slots to the given statuses and codes.""" user_ids = ",".join(user_ids) status = ",".join(status) codes = ",".join(codes if codes else []) try: self.send_command(self.CMD_USER_CODE_SET, '&id={}&status={}&code={}' .format(user_ids, status, codes)) except: return False if verify: timeout = 0 first_user = user_ids[0] first_status = status[0] first_code = codes[0] while not self.is_code_set(first_user, first_status, first_code): # Assume that if the first code was set correctly, all codes were. if timeout >= 20: return False await asyncio.sleep(1) timeout += 1 return True async def remove_single_code(self, user_id, verify=True): """Set a single code to unoccupied status.""" return await self.set_codes([user_id], [self.STATUS_UNOCCUPIED], verify=verify) async def disable_single_code(self, user_id, code, verify=True): """Set a single code to occupied/disabled status.""" return await self.set_codes([user_id], [self.STATUS_UNOCCUPIED], codes=[code], verify=verify) async def get_all_users(self, active=False): """Get a dictionary of the status of all users in the lock.""" cmd = self.CMD_USER_CODE_USERS_ACTIVE_GET if active else self.CMD_USER_CODE_USERS_PASSIVE_GET max_users = int(self.ret_command(cmd).get('user_cnt')) users = {} for i in range(1, max_users + 1): cmd = self.CMD_USER_CODE_ACTIVE_GET if active else self.CMD_USER_CODE_PASSIVE_GET code = self.ret_command(cmd, arg='&id={}'.format(i)) users[str(i)] = { "status": code.get('status'), "code": code.get('code'), "update": code.get('utime'), } return users def is_code_set(self, user_id, status, code): """Check if a code and status are set in a given id.""" code_obj = self.ret_command(self.CMD_USER_CODE_ACTIVE_GET, '&id={}'.format(user_id)) if status == self.STATUS_UNOCCUPIED: return code_obj.get('status') == status return code_obj.get('status') == status and code_obj.get('code') == code class zwAlarm(zwInterface): """Representation of a Z-Wave Alarm Command Class.""" CMD_ALARM_ACTIVE_GET = 2 CMD_ALARM_PASSIVE_GET = 3 def send_command(self, cmd, arg='', dev='alrm'): """Send a command to the Alarm Command Class.""" super(self, zwAlarm).send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='alrm'): """Send a command to the Alarm Command Class that returns data.""" return super(self, zwAlarm).ret_command(cmd, arg=arg, dev=dev) def get_alarm_status(self, alarm_vtype): """Get the last alarm status of an specific alarm type.""" status = self.ret_command(self.CMD_ALARM_ACTIVE_GET, '&vtype={}'.format(alarm_vtype)) name = self.get_event_description(status.get('vtype'), status.get('ztype'), status.get('level'), status.get('event')) return {'alarm_vtype': status.get('vtype'), 'event_description': name, 'ocurred_at': status.get('utime')} def get_last_alarm(self): """Get the last alarm registered on the lock.""" status = self.ret_command(self.CMD_ALARM_PASSIVE_GET, '&ztype=255') name = self.get_event_description(status.get('vtype'), status.get('ztype'), status.get('level'), status.get('event')) return {'alarm_vtype': status.get('vtype'), 'event_description': name, 'ocurred_at': status.get('utime')} def get_event_description(self, vtype, level, ztype, event): """Get the event description given the types and levels.""" name = EVENTS.get(ztype, dict()).get(event) if name is None: name = EVENTS["0"][vtype].get(level) if name is None: name = EVENTS[ztype][vtype]["default"].format(level) return name
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/lock.py
lock.py
from . import zwInterface class zwBattery(zwInterface): """Representation of a Z-Wave Battery Command Class.""" CMD_BATTERY_ACTIVE_GET = 2 CMD_BATTERY_PASSIVE_GET = 3 def send_command(self, cmd, arg='', dev='battery'): """Send a command to the Battery Command Class.""" super().send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='battery'): """Send a command to the Battery Command Class that returns data.""" return super().ret_command(cmd, arg=arg, dev=dev) def get_status(self, active=False): """Get the battery level of the lock.""" cmd = self.CMD_BATTERY_ACTIVE_GET if active else self.CMD_BATTERY_PASSIVE_GET status = self.ret_command(cmd) self.status = int(status.get('level')) return {'battery': self.status}
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/battery.py
battery.py
class zwInterface: """Representation of a Z-Wave Command Class as an interface.""" CMD_BASIC_SETUP = 1 CMD_BASIC_ACTIVE_GET = 2 CMD_BASIC_PASSIVE_GET = 3 CMD_BASIC_SET = 4 def __init__(self, zware, desc, type_id, name, virtual_version, real_if_version, secure, unsecure): """Initialize a z-wave Command Class as an interface.""" self.zware = zware # Properties of an interface. self.id = desc self.type_id = type_id self.name = name self.virtual_version = virtual_version self.real_version = real_if_version self.secure = (int(secure) == 1) self.unsecure = (int(unsecure) == 1) self.status = None def send_command(self, cmd, arg='', dev='basic'): """ Send a command to an interface. Override this function for each specific Command Class. """ self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) def ret_command(self, cmd, arg='', dev='basic'): """ Send a command to an interface that returns data. Override this function for each specific Command Class. """ r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_BASIC_ACTIVE_GET or cmd == self.CMD_BASIC_PASSIVE_GET: return r.find('./zwif/' + dev) return r
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/base.py
base.py
from . import zwInterface class zwLock(zwInterface): """Representation of a Z-Wave Lock Command Class.""" CMD_OPEN_DOOR = 0 CMD_CLOSE_DOOR = 255 CMD_DLOCK_SETUP = 1 CMD_DLOCK_OP_ACTIVE_GET = 2 CMD_DLOCK_OP_PASSIVE_GET = 3 CMD_DLOCK_OP_SET = 4 CMD_DLOCK_CFG_ACTIVE_GET = 5 CMD_DLOCK_CFG_PASSIVE_GET = 6 def send_command(self, cmd, arg='', dev='dlck'): """Send a command to the Doorlock Command Class.""" super().send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='dlck'): """Send a command to the Doorlock Command Class that returns data.""" r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_DLOCK_OP_ACTIVE_GET or cmd == self.CMD_DLOCK_OP_PASSIVE_GET: return r.find('./zwif/' + dev + '_op') elif cmd == self.CMD_DLOCK_CFG_ACTIVE_GET or cmd == self.CMD_DLOCK_CFG_PASSIVE_GET: return r.find('./zwif/' + dev + '_cfg') return r def get_status(self, active=False): """Get status from the Doorlock Command Class.""" cmd = self.CMD_DLOCK_OP_ACTIVE_GET if active else self.CMD_DLOCK_OP_PASSIVE_GET sts_lock_door = self.ret_command(cmd) self.status = (int(sts_lock_door.get('mode')) == self.CMD_CLOSE_DOOR) return {'is_locked': self.status} def lock(self): """Operate the Doorlock Command Class to lock.""" self.send_command(self.CMD_DLOCK_SETUP) # Select this Command Class. self.send_command(self.CMD_DLOCK_OP_SET, '&mode=' + str(self.CMD_CLOSE_DOOR)) def unlock(self): """Operate the Doorlock Command Class to unlock.""" self.send_command(self.CMD_DLOCK_SETUP) # Select this Command Class. self.send_command(self.CMD_DLOCK_OP_SET, '&mode=' + str(self.CMD_OPEN_DOOR)) class zwLockLogging(zwInterface): """Representation of a Z-Wave Lock Logging Command Class.""" CMD_DLOCK_LOG_ACTIVE_GET = 2 CMD_DLOCK_LOG_PASSIVE_GET = 3 CMD_DLOCK_LOG_SUP_ACTIVE_GET = 2 CMD_DLOCK_LOG_SUP_PASSIVE_GET = 3 def send_command(self, cmd, arg='', dev='dlck_log'): """Send a command to the Doorlock Command Class.""" super().send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='dlck_log'): """Send a command to the Doorlock Command Class that returns data.""" r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_DLOCK_LOG_SUP_ACTIVE_GET or cmd == self.CMD_DLOCK_LOG_SUP_PASSIVE_GET: return r.find('./zwif/' + dev + '_sup') return r class zwScheduleEntry(zwInterface): """ Representation of a Z-Wave Schedule Entry Lock Command Class. Not supported by Z-Ware API yet. """ def send_command(self, cmd, arg='', dev=''): """Send a command to the Schedule Entry Lock Command Class.""" raise NotImplementedError def ret_command(self, cmd, arg='', dev=''): """Send a command to the Schedule Entry Lock Command Class that returns data.""" raise NotImplementedError
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/doorlock.py
doorlock.py
from . import zwInterface EVENTS = { "0": { "9": { "1": "Deadbolt jammed while locking", "2": "Deadbolt jammed while unlocking", }, "18": { "default": "Keypad Lock with user_id {}", }, "19": { "default": "Keypad Unlock with user_id {}", }, "21": { "1": "Manual Lock by Key Cylinder or Thumb-Turn", "2": "Manual Lock by Touch Function", "3": "Manual Lock by Inside Button", }, "22": { "1": "Manual Unlock Operation", }, "24": { "1": "RF Lock Operation", }, "25": { "1": "RF Unlock Operation", }, "27": { "1": "Auto re-lock cycle complete", }, "33": { "default": "Single user code deleted with user_id {}", }, "38": { "default": "Non access code entered with user_id {}", }, "96": { "default": "Daily Schedule has been set/erased for user_id {}" }, "97": { "default": "Daily Schedule has been enabled/disabled for user_id {}" }, "98": { "default": "Yearly Schedule has been set/erased for user_id {}" }, "99": { "default": "Yearly Schedule has been enabled/disabled for user_id {}" }, "100": { "default": "All Schedules have been set/erased for user_id {}" }, "101": { "default": "All Schedules have been enabled/disabled for user_id {}" }, "112": { "default": "New user code added with user_id {}", "0": "Master Code was changed at keypad", "251": "Master Code was changed over RF", }, "113": { "0": "Duplicate Master Code error", "default": "Duplicate Pin-Code error with user_id {}", }, "130": { "0": "Door Lock needs Time Set" }, "131": { "default": "Disabled user_id {} code was entered at the keypad" }, "132": { "default": "Valid user_id {} code was entered outside of schedule" }, "161": { "1": "Keypad attempts exceed limit", "2": "Front Escutcheon removed from main", "3": "Master Code attempts exceed limit", }, "167": { "default": "Low Battery Level {}", }, "168": { "default": "Critical Battery Level {}", } }, "6": { "0": "State idle", "1": "Manual Lock Operation", "2": "Manual Unlock Operation", "3": "RF Lock Operation", "4": "RF Unlock Operation", "5": "Keypad Lock Operation", "6": "Keypad Unlock Operation", "7": "Manual Not Fully Locked Operation", "8": "RF Not Fully Locked Operation", "9": "Auto Lock Locked Operation", "10": "Auto Lock Not Fully Operation", "11": "Lock Jammed", "12": "All user codes deleted", "13": "Single user code deleted", "14": "New user code added", "15": "New user code not added due to duplicate code", "16": "Keypad temporary disabled", "17": "Keypad busy", "18": "New Program code Entered - Unique code for lock configuration", "19": "Manually Enter user Access code exceeds code limit", "20": "Unlock By RF with invalid user code", "21": "Locked by RF with invalid user codes", "22": "Window/Door is open", "23": "Window/Door is closed", "24": "Window/door handle is open", "25": "Window/door handle is closed", "32": "Messaging User Code entered via keypad", "64": "Barrier performing Initialization process", "65": "Barrier operation (Open / Close) force has been exceeded.", "66": "Barrier motor has exceeded manufacturer’s operational time limit", "67": "Barrier operation has exceeded physical mechanical limits.", "68": "Barrier unable to perform requested operation due to UL requirements", "69": "Barrier Unattended operation has been disabled per UL requirements", "70": "Barrier failed to perform Requested operation, device malfunction", "71": "Barrier Vacation Mode", "72": "Barrier Safety Beam Obstacle", "73": "Barrier Sensor Not Detected / Supervisory Error", "74": "Barrier Sensor Low Battery Warning", "75": "Barrier detected short in Wall Station wires", "76": "Barrier associated with non-Z-wave remote control", "254": "Unknown Event" }, "8": { "1": "Door Lock needs Time Set", "10": "Low Battery", "11": "Critical Battery Level" } } def get_event_description(vtype, level, ztype, event): """Get the event description given the types and levels.""" vtype_ev = EVENTS["0"].get(vtype) name = None if vtype_ev: name = vtype_ev.get(level) if name is None: name = vtype_ev.get("default", "{}").format(level) if name is None or name == str(level): name = EVENTS.get(ztype, dict()).get(event) return name class zwAlarm(zwInterface): """Representation of a Z-Wave Alarm Command Class.""" CMD_ALARM_ACTIVE_GET = 2 CMD_ALARM_PASSIVE_GET = 3 def send_command(self, cmd, arg='', dev='alrm'): """Send a command to the Alarm Command Class.""" super().send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='alrm'): """Send a command to the Alarm Command Class that returns data.""" return super().ret_command(cmd, arg=arg, dev=dev) def get_alarm_status(self, alarm_vtype): """Get the last alarm status of an specific alarm type.""" status = self.ret_command(self.CMD_ALARM_ACTIVE_GET, '&vtype={}'.format(alarm_vtype)) name = get_event_description(status.get('vtype'), status.get('ztype'), status.get('level'), status.get('event')) return {'alarm_vtype': status.get('vtype'), 'event_description': name, 'ocurred_at': status.get('utime')} def get_last_alarm(self): """Get the last alarm registered on the lock.""" status = self.ret_command(self.CMD_ALARM_PASSIVE_GET, '&ztype=255') if status is None: return {'event_description': 'Offline'} name = get_event_description(status.get('vtype'), status.get('level'), status.get('ztype'), status.get('event')) return { 'alarm_vtype': status.get('vtype'), 'alarm_level': status.get('level'), 'alarm_ztype': status.get('ztype'), 'alarm_event': status.get('event'), 'event_description': name, 'occurred_at': status.get('utime') }
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/alarm.py
alarm.py
import time from . import zwInterface class zwUserCode(zwInterface): """Representation of a Z-Wave User Code Command Class.""" CMD_USER_CODE_ACTIVE_GET = 1 CMD_USER_CODE_PASSIVE_GET = 2 CMD_USER_CODE_SET = 3 CMD_USER_CODE_USERS_ACTIVE_GET = 4 CMD_USER_CODE_USERS_PASSIVE_GET = 5 CMD_USER_CODE_MASTER_ACTIVE_GET = 11 CMD_USER_CODE_MASTER_PASSIVE_GET = 12 CMD_USER_CODE_MASTER_SET = 13 STATUS_UNOCCUPIED = 0 STATUS_OCCUPIED_ENABLED = 1 STATUS_OCCUPIED_DISABLED = 3 STATUS_NON_ACCESS_USER = 4 def send_command(self, cmd, arg='', dev='usrcod'): """Send a command to the User Code Command Class.""" super().send_command(cmd, arg=arg, dev=dev) def ret_command(self, cmd, arg='', dev='usrcod'): """Send a command to the User Code Command Class that returns data.""" r = self.zware.zw_api('zwif_' + dev, 'cmd={}&ifd={}'.format(cmd, self.id) + arg) if cmd == self.CMD_USER_CODE_ACTIVE_GET or cmd == self.CMD_USER_CODE_PASSIVE_GET: return r.find('./zwif/usrcod') elif cmd == self.CMD_USER_CODE_USERS_ACTIVE_GET or cmd == self.CMD_USER_CODE_USERS_PASSIVE_GET: return r.find('./zwif/usrcod_sup') return r def get_master_code(self, active=False): """Get the master code. Only if the specific devices' User Code Command Class supports it.""" cmd = self.CMD_USER_CODE_MASTER_ACTIVE_GET if active else self.CMD_USER_CODE_MASTER_PASSIVE_GET status = self.ret_command(cmd) return {'master_code': status.get('master_code')} def set_master_code(self, code, verify=True): """Set the master code. Only if the specific devices' User Code Command Class supports it.""" self.send_command(self.CMD_USER_CODE_MASTER_SET, arg='&master_code={}'.format(code)) if verify: timeout = 0 while self.ret_command(self.CMD_USER_CODE_MASTER_ACTIVE_GET).get('master_code') != str(code): if timeout >= 20: return False time.sleep(1) timeout += 1 return True def set_codes(self, user_ids: list, status: list, codes=None, verify=True): """Set a list of code slots to the given statuses and codes.""" first_user = user_ids[0] first_status = status[0] first_code = codes[0] if codes else None user_ids = ",".join(user_ids) status = ",".join(status) codes = ",".join(codes if codes else []) self.send_command(self.CMD_USER_CODE_SET, '&id={}&status={}&code={}' .format(user_ids, status, codes)) if verify: timeout = 0 while not self.is_code_set(first_user, first_status, first_code): # Assume that if the first code was set correctly, all codes were. if timeout >= 20: return False time.sleep(1) timeout += 1 return True def get_code(self, user_id, active=False): """Get the code from a user_id and its status.""" cmd = self.CMD_USER_CODE_ACTIVE_GET if active else self.CMD_USER_CODE_PASSIVE_GET status = self.ret_command(cmd, arg='&id={}'.format(user_id)) if status is None: return {"user_id": user_id, "status": self.STATUS_UNOCCUPIED, "code": None, "error": "Not found"} return {"user_id": status.get("id"), "status": status.get("status"), "code": status.get("code")} def remove_single_code(self, user_id, verify=True): """Set a single code to unoccupied status.""" return self.set_codes([user_id], [str(self.STATUS_UNOCCUPIED)], verify=verify) def disable_single_code(self, user_id, code, verify=True): """Set a single code to occupied/disabled status.""" return self.set_codes([user_id], [str(self.STATUS_UNOCCUPIED)], codes=[code], verify=verify) def get_all_users(self, active=False): """Get a dictionary of the status of all users in the lock.""" cmd = self.CMD_USER_CODE_USERS_ACTIVE_GET if active else self.CMD_USER_CODE_USERS_PASSIVE_GET max_users = int(self.ret_command(cmd).get('user_cnt')) users = {} for i in range(1, max_users + 1): cmd = self.CMD_USER_CODE_ACTIVE_GET if active else self.CMD_USER_CODE_PASSIVE_GET code = self.ret_command(cmd, arg='&id={}'.format(i)) if code is not None: users[str(i)] = { "status": code.get('status'), "code": code.get('code'), "update": code.get('utime'), } return users def is_code_set(self, user_id, status, code): """Check if a code and status are set in a given id.""" code_obj = self.ret_command(self.CMD_USER_CODE_ACTIVE_GET, '&id={}'.format(user_id)) if code_obj is None: return False if status == str(self.STATUS_UNOCCUPIED): return code_obj.get('status') == status return code_obj.get('status') == status and code_obj.get('code') == code
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/usercode.py
usercode.py
from .base import * from .alarm import * from .battery import * from .doorlock import * from .usercode import *
zware-api
/zware_api-0.0.25.tar.gz/zware_api-0.0.25/zware_api/interfaces/__init__.py
__init__.py
#!/usr/bin/env bash cd zwatershed rm zwatershed.so python setup.py build_ext --inplace printf "BUILD COMPLETE\n" cd ..
zwatershed
/zwatershed-0.10.tar.gz/zwatershed-0.10/make.sh
make.sh
# convolutional network metric scripts - Code for fast watersheds. Code is based around code from https://bitbucket.org/poozh/watershed described in http://arxiv.org/abs/1505.00249. For use in https://github.com/naibaf7/PyGreentea. # building ### conda - `conda install -c conda-forge zwatershed` ### pip [<img src="https://img.shields.io/pypi/v/zwatershed.svg?maxAge=2592000">](https://pypi.python.org/pypi/zwatershed/) - `pip install zwatershed` ### from source - clone the repository - run ./make.sh ### requirements - numpy, h5py, cython - if using parallel watershed, also requires multiprocessing or pyspark - in order to build the cython, requires a c++ compiler and boost # function api - `(segs, rand) = zwatershed_and_metrics(segTrue, aff_graph, eval_thresh_list, seg_save_thresh_list)` - *returns segmentations and metrics* - `segs`: list of segmentations - `len(segs) == len(seg_save_thresh_list)` - `rand`: dict - `rand['V_Rand']`: V_Rand score (scalar) - `rand['V_Rand_split']`: list of score values - `len(rand['V_Rand_split']) == len(eval_thresh_list)` - `rand['V_Rand_merge']`: list of score values, - `len(rand['V_Rand_merge']) == len(eval_thresh_list)` - `segs = zwatershed(aff_graph, seg_save_thresh_list)` - *returns segmentations* - `segs`: list of segmentations - `len(segs) == len(seg_save_thresh_list)` ##### These methods have versions which save the segmentations to hdf5 files instead of returning them - `rand = zwatershed_and_metrics_h5(segTrue, aff_graph, eval_thresh_list, seg_save_thresh_list, seg_save_path)` - `zwatershed_h5(aff_graph, eval_thresh_list, seg_save_path)` ##### All 4 methods have versions which take an edgelist representation of the affinity graph - `(segs, rand) = zwatershed_and_metrics_arb(segTrue, node1, node2, edgeWeight, eval_thresh_list, seg_save_thresh_list)` - `segs = zwatershed_arb(seg_shape, node1, node2, edgeWeight, seg_save_thresh_list)` - `rand = zwatershed_and_metrics_h5_arb(segTrue, node1, node2, edgeWeight, eval_thresh_list, seg_save_thresh_list, seg_save_path)` - `zwatershed_h5_arb(seg_shape, node1, node2, edgeWeight, eval_thresh_list, seg_save_path)` # parallel watershed - 4 steps - *a full example is given in par_ex.ipynb* 1. Partition the subvolumes - `partition_data = partition_subvols(pred_file,out_folder,max_len)` - evenly divides the data in *pred_file* with the constraint that no dimension of any subvolume is longer than max_len 2. Zwatershed the subvolumes 1. `eval_with_spark(partition_data[0])` - *with spark* 2. `eval_with_par_map(partition_data[0],NUM_WORKERS)` - *with python multiprocessing map* - after evaluating, subvolumes will be saved into the out\_folder directory named based on their smallest indices in each dimension (ex. path/to/out\_folder/0\_0\_0\_vol) 3. Stitch the subvolumes together - `stitch_and_save(partition_data,outname)` - stitch together the subvolumes in partition_data - save to the hdf5 file outname - outname['starts'] = list of min_indices of each subvolume - outname['ends'] = list of max_indices of each subvolume - outname['seg'] = full stitched segmentation - outname['seg_sizes'] = array of size of each segmentation - outname['rg_i'] = region graph for ith subvolume 4. Threshold individual subvolumes by merging - `seg_merged = merge_by_thresh(seg,seg_sizes,rg,thresh)` - load in these areguments from outname
zwatershed
/zwatershed-0.10.tar.gz/zwatershed-0.10/README.md
README.md
from distutils.sysconfig import get_config_vars, get_config_var, get_python_inc from setuptools import setup, Extension from setuptools.command.build_ext import build_ext as _build_ext import os include_dirs = [ os.path.join(os.path.dirname(os.path.abspath(__file__)), "zwatershed"), os.path.dirname(get_python_inc()), get_python_inc() ] library_dirs = [ os.path.join(os.path.dirname(os.path.abspath(__file__)), "zwatershed"), get_config_var("LIBDIR") ] # Remove the "-Wstrict-prototypes" compiler option, which isn't valid for C++. cfg_vars = get_config_vars() if "CFLAGS" in cfg_vars: cfg_vars["CFLAGS"] = cfg_vars["CFLAGS"].replace("-Wstrict-prototypes", "") class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: __builtins__.__NUMPY_SETUP__ = False import numpy self.include_dirs.append(numpy.get_include()) setup(name='zwatershed', version='0.10', description='Fast watersheds', url='https://github.com/TuragaLab/zwatershed', author='Chandan Singh', author_email='csinva@virginia.edu', cmdclass=dict( build_ext=build_ext ), license='MIT', install_requires=['cython','numpy','h5py'], setup_requires=['cython','numpy'], packages=['zwatershed'], ext_modules = [Extension("zwatershed.zwatershed", ["zwatershed/zwatershed.pyx", "zwatershed/zwatershed_main.cpp"], include_dirs=include_dirs, library_dirs=library_dirs, language='c++', # std= 'c++11', extra_link_args=["-std=c++11"], extra_compile_args=["-std=c++11", "-w"])], zip_safe=False)
zwatershed
/zwatershed-0.10.tar.gz/zwatershed-0.10/setup.py
setup.py
"""Provide Event base classes for Z-Wave JS.""" from __future__ import annotations import logging from dataclasses import dataclass, field from typing import Callable, Literal try: from pydantic.v1 import BaseModel except ImportError: from pydantic import BaseModel LOGGER = logging.getLogger(__package__) class BaseEventModel(BaseModel): """Base model for an event.""" source: Literal["controller", "driver", "node"] event: str @dataclass class Event: """Represent an event.""" type: str data: dict = field(default_factory=dict) class EventBase: """Represent a Z-Wave JS base class for event handling models.""" def __init__(self) -> None: """Initialize event base.""" self._listeners: dict[str, list[Callable]] = {} def on( # pylint: disable=invalid-name self, event_name: str, callback: Callable ) -> Callable: """Register an event callback.""" listeners: list = self._listeners.setdefault(event_name, []) listeners.append(callback) def unsubscribe() -> None: """Unsubscribe listeners.""" if callback in listeners: listeners.remove(callback) return unsubscribe def once(self, event_name: str, callback: Callable) -> Callable: """Listen for an event exactly once.""" def event_listener(data: dict) -> None: unsub() callback(data) unsub = self.on(event_name, event_listener) return unsub def emit(self, event_name: str, data: dict) -> None: """Run all callbacks for an event.""" for listener in self._listeners.get(event_name, []).copy(): listener(data) def _handle_event_protocol(self, event: Event) -> None: """Process an event based on event protocol.""" handler = getattr(self, f"handle_{event.type.replace(' ', '_')}", None) if handler is None: LOGGER.debug("Received unknown event: %s", event) return handler(event)
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/event.py
event.py
"""Basic CLI to test Z-Wave JS server.""" from __future__ import annotations import argparse import asyncio import logging import sys import aiohttp from .client import Client from .dump import dump_msgs from .version import get_server_version logger = logging.getLogger(__package__) def get_arguments() -> argparse.Namespace: """Get parsed passed in arguments.""" parser = argparse.ArgumentParser(description="Z-Wave JS Server Python") parser.add_argument("--debug", action="store_true", help="Log with debug level") parser.add_argument( "--server-version", action="store_true", help="Print the version of the server" ) parser.add_argument( "--dump-state", action="store_true", help="Dump the driver state" ) parser.add_argument( "--event-timeout", help="How long to listen for events when dumping state", ) parser.add_argument( "url", type=str, help="URL of server, ie ws://localhost:3000", ) arguments = parser.parse_args() return arguments async def start_cli() -> None: """Run main.""" args = get_arguments() level = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=level) async with aiohttp.ClientSession() as session: if args.server_version: await print_version(args, session) elif args.dump_state: await handle_dump_state(args, session) else: await connect(args, session) async def print_version( args: argparse.Namespace, session: aiohttp.ClientSession ) -> None: """Print the version of the server.""" logger.setLevel(logging.WARNING) version = await get_server_version(args.url, session) print("Driver:", version.driver_version) print("Server:", version.server_version) print("Home ID:", version.home_id) async def handle_dump_state( args: argparse.Namespace, session: aiohttp.ClientSession ) -> None: """Dump the state of the server.""" timeout = None if args.event_timeout is None else float(args.event_timeout) msgs = await dump_msgs(args.url, session, timeout=timeout) for msg in msgs: print(msg) async def connect(args: argparse.Namespace, session: aiohttp.ClientSession) -> None: """Connect to the server.""" async with Client(args.url, session) as client: driver_ready = asyncio.Event() asyncio.create_task(on_driver_ready(client, driver_ready)) await client.listen(driver_ready) async def on_driver_ready(client: Client, driver_ready: asyncio.Event) -> None: """Act on driver ready.""" await driver_ready.wait() assert client.driver # Set up listeners on new nodes client.driver.controller.on( "node added", lambda event: event["node"].on("value updated", log_value_updated), ) # Set up listeners on existing nodes for node in client.driver.controller.nodes.values(): node.on("value updated", log_value_updated) def log_value_updated(event: dict) -> None: """Log node value changes.""" node = event["node"] value = event["value"] if node.device_config: description = node.device_config.description else: description = f"{node.device_class.generic} (missing device config)" logger.info( "Node %s %s (%s) changed to %s", description, value.property_name or "", value.value_id, value.value, ) def main() -> None: """Run main.""" try: asyncio.run(start_cli()) except KeyboardInterrupt: pass sys.exit(0) if __name__ == "__main__": main()
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/__main__.py
__main__.py
"""Client.""" from __future__ import annotations import asyncio import logging import pprint import uuid from collections import defaultdict from copy import deepcopy from datetime import datetime from operator import itemgetter from types import TracebackType from typing import Any, cast from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType, client_exceptions from .const import ( MAX_SERVER_SCHEMA_VERSION, MIN_SERVER_SCHEMA_VERSION, PACKAGE_NAME, __version__, ) from .event import Event from .exceptions import ( CannotConnect, ConnectionClosed, ConnectionFailed, FailedCommand, FailedZWaveCommand, InvalidMessage, InvalidServerVersion, InvalidState, NotConnected, ) from .model.driver import Driver from .model.version import VersionInfo, VersionInfoDataType SIZE_PARSE_JSON_EXECUTOR = 8192 # Message IDs INITIALIZE_MESSAGE_ID = "initialize" GET_INITIAL_LOG_CONFIG_MESSAGE_ID = "get-initial-log-config" START_LISTENING_MESSAGE_ID = "start-listening" LISTEN_MESSAGE_IDS = ( GET_INITIAL_LOG_CONFIG_MESSAGE_ID, INITIALIZE_MESSAGE_ID, START_LISTENING_MESSAGE_ID, ) class Client: """Class to manage the IoT connection.""" def __init__( self, ws_server_url: str, aiohttp_session: ClientSession, schema_version: int = MAX_SERVER_SCHEMA_VERSION, additional_user_agent_components: dict[str, str] | None = None, record_messages: bool = False, ): """Initialize the Client class.""" self.ws_server_url = ws_server_url self.aiohttp_session = aiohttp_session self.driver: Driver | None = None # The WebSocket client self._client: ClientWebSocketResponse | None = None # Version of the connected server self.version: VersionInfo | None = None self.schema_version: int = schema_version self.additional_user_agent_components = { PACKAGE_NAME: __version__, **(additional_user_agent_components or {}), } self._logger = logging.getLogger(__package__) self._loop = asyncio.get_running_loop() self._result_futures: dict[str, asyncio.Future] = {} self._shutdown_complete_event: asyncio.Event | None = None self._record_messages = record_messages self._recorded_commands: defaultdict[str, dict] = defaultdict(dict) self._recorded_events: list[dict] = [] def __repr__(self) -> str: """Return the representation.""" prefix = "" if self.connected else "not " return f"{type(self).__name__}(ws_server_url={self.ws_server_url!r}, {prefix}connected)" @property def connected(self) -> bool: """Return if we're currently connected.""" return self._client is not None and not self._client.closed @property def recording_messages(self) -> bool: """Return True if messages are being recorded.""" return self._record_messages async def async_send_command( self, message: dict[str, Any], require_schema: int | None = None ) -> dict: """Send a command and get a response.""" if require_schema is not None and require_schema > self.schema_version: assert self.version raise InvalidServerVersion( self.version, require_schema, "Command not available due to incompatible server version. Update the Z-Wave " f"JS Server to a version that supports at least api schema {require_schema}.", ) future: "asyncio.Future[dict]" = self._loop.create_future() message_id = message["messageId"] = uuid.uuid4().hex self._result_futures[message_id] = future await self._send_json_message(message) try: return await future finally: self._result_futures.pop(message_id) async def async_send_command_no_wait( self, message: dict[str, Any], require_schema: int | None = None ) -> None: """Send a command without waiting for the response.""" if require_schema is not None and require_schema > self.schema_version: assert self.version raise InvalidServerVersion( self.version, require_schema, "Command not available due to incompatible server version. Update the Z-Wave " f"JS Server to a version that supports at least api schema {require_schema}.", ) message["messageId"] = uuid.uuid4().hex await self._send_json_message(message) async def connect(self) -> None: """Connect to the websocket server.""" if self.driver is not None: raise InvalidState("Re-connected with existing driver") self._logger.debug("Trying to connect") try: self._client = await self.aiohttp_session.ws_connect( self.ws_server_url, heartbeat=55, compress=15, max_msg_size=0, ) except ( client_exceptions.WSServerHandshakeError, client_exceptions.ClientError, ) as err: raise CannotConnect(err) from err self.version = version = VersionInfo.from_message( cast(VersionInfoDataType, await self._receive_json_or_raise()) ) # basic check for server schema version compatibility if ( self.version.min_schema_version > MAX_SERVER_SCHEMA_VERSION or self.version.max_schema_version < MIN_SERVER_SCHEMA_VERSION ): await self._client.close() assert self.version raise InvalidServerVersion( self.version, MIN_SERVER_SCHEMA_VERSION, f"Z-Wave JS Server version ({self.version.server_version}) is " "incompatible. Update the Z-Wave JS Server to a version that supports " f"at least api schema {MIN_SERVER_SCHEMA_VERSION}", ) # store the (highest possible) schema version we're going to use/request # this is a bit future proof as we might decide to use a pinned version at some point # for now we just negotiate the highest available schema version and # guard incompatibility with the MIN_SERVER_SCHEMA_VERSION if self.version.max_schema_version < MAX_SERVER_SCHEMA_VERSION: self.schema_version = self.version.max_schema_version self._logger.info( "Connected to Home %s (Server %s, Driver %s, Using Schema %s)", version.home_id, version.server_version, version.driver_version, self.schema_version, ) async def initialize(self) -> None: """Initialize connection to server by setting schema version and user agent.""" assert self._client # set preferred schema version on the server # note: we already check for (in)compatible schemas in the connect call await self._send_json_message( { "command": "initialize", "messageId": INITIALIZE_MESSAGE_ID, "schemaVersion": self.schema_version, "additionalUserAgentComponents": self.additional_user_agent_components, } ) set_api_msg = await self._receive_json_or_raise() if not set_api_msg["success"]: # this should not happen, but just in case await self._client.close() raise FailedCommand(set_api_msg["messageId"], set_api_msg["errorCode"]) async def listen(self, driver_ready: asyncio.Event) -> None: """Start listening to the websocket.""" if not self.connected: raise InvalidState("Not connected when start listening") assert self._client try: await self.initialize() await self._send_json_message( { "command": "driver.get_log_config", "messageId": GET_INITIAL_LOG_CONFIG_MESSAGE_ID, } ) log_msg = await self._receive_json_or_raise() # this should not happen, but just in case if not log_msg["success"]: await self._client.close() raise FailedCommand(log_msg["messageId"], log_msg["errorCode"]) # send start_listening command to the server # we will receive a full state dump and from now on get events await self._send_json_message( {"command": "start_listening", "messageId": START_LISTENING_MESSAGE_ID} ) state_msg = await self._receive_json_or_raise() if not state_msg["success"]: await self._client.close() raise FailedCommand(state_msg["messageId"], state_msg["errorCode"]) self.driver = cast( Driver, await self._loop.run_in_executor( None, Driver, self, state_msg["result"]["state"], log_msg["result"]["config"], ), ) driver_ready.set() self._logger.info( "Z-Wave JS initialized. %s nodes", len(self.driver.controller.nodes) ) await self.receive_until_closed() except ConnectionClosed: pass finally: self._logger.debug("Listen completed. Cleaning up") for future in self._result_futures.values(): future.cancel() self._result_futures.clear() if not self._client.closed: await self._client.close() if self._shutdown_complete_event: self._shutdown_complete_event.set() async def disconnect(self) -> None: """Disconnect the client.""" self._logger.debug("Closing client connection") if not self.connected: return assert self._client # 'listen' was never called if self.driver is None: await self._client.close() return self._shutdown_complete_event = asyncio.Event() await self._client.close() await self._shutdown_complete_event.wait() self._shutdown_complete_event = None self.driver = None def begin_recording_messages(self) -> None: """Begin recording messages for replay later.""" if self._record_messages: raise InvalidState("Already recording messages") self._record_messages = True def end_recording_messages(self) -> list[dict]: """End recording messages and return messages that were recorded.""" if not self._record_messages: raise InvalidState("Not recording messages") self._record_messages = False data = sorted( (*self._recorded_commands.values(), *self._recorded_events), key=itemgetter("ts"), ) self._recorded_commands.clear() self._recorded_events.clear() return list(data) async def receive_until_closed(self) -> None: """Receive messages until client is closed.""" assert self._client while not self._client.closed: data = await self._receive_json_or_raise() self._handle_incoming_message(data) async def _receive_json_or_raise(self) -> dict: """Receive json or raise.""" assert self._client msg = await self._client.receive() if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING): raise ConnectionClosed("Connection was closed.") if msg.type == WSMsgType.ERROR: raise ConnectionFailed() if msg.type != WSMsgType.TEXT: raise InvalidMessage(f"Received non-Text message: {msg.type}") try: if len(msg.data) > SIZE_PARSE_JSON_EXECUTOR: data: dict = await self._loop.run_in_executor(None, msg.json) else: data = msg.json() except ValueError as err: raise InvalidMessage("Received invalid JSON.") from err if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug("Received message:\n%s\n", pprint.pformat(msg)) return data def _handle_incoming_message(self, msg: dict) -> None: """Handle incoming message. Run all async tasks in a wrapper to log appropriately. """ if msg["type"] == "result": future = self._result_futures.get(msg["messageId"]) if future is None: # no listener for this result return if self._record_messages and msg["messageId"] not in LISTEN_MESSAGE_IDS: self._recorded_commands[msg["messageId"]].update( { "result_ts": datetime.utcnow().isoformat(), "result_msg": deepcopy(msg), } ) if msg["success"]: future.set_result(msg["result"]) return if msg["errorCode"] != "zwave_error": err = FailedCommand(msg["messageId"], msg["errorCode"]) else: err = FailedZWaveCommand( msg["messageId"], msg["zwaveErrorCode"], msg["zwaveErrorMessage"] ) future.set_exception(err) return if msg["type"] != "event": # Can't handle self._logger.debug( "Received message with unknown type '%s': %s", msg["type"], msg, ) return if self._record_messages: self._recorded_events.append( { "record_type": "event", "ts": datetime.utcnow().isoformat(), "type": msg["event"]["event"], "event_msg": deepcopy(msg), } ) event = Event(type=msg["event"]["event"], data=msg["event"]) self.driver.receive_event(event) # type: ignore async def _send_json_message(self, message: dict[str, Any]) -> None: """Send a message. Raises NotConnected if client not connected. """ if not self.connected: raise NotConnected if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug("Publishing message:\n%s\n", pprint.pformat(message)) assert self._client assert "messageId" in message if self._record_messages and message["messageId"] not in LISTEN_MESSAGE_IDS: # We don't need to deepcopy command_msg because it is always released by # the caller after the command is sent. self._recorded_commands[message["messageId"]].update( { "record_type": "command", "ts": datetime.utcnow().isoformat(), "command": message["command"], "command_msg": message, } ) await self._client.send_json(message) async def async_start_listening_logs(self) -> None: """Send command to start listening to log events.""" await self.async_send_command( {"command": "start_listening_logs"}, require_schema=31 ) async def async_stop_listening_logs(self) -> None: """Send command to stop listening to log events.""" await self.async_send_command( {"command": "stop_listening_logs"}, require_schema=31 ) async def __aenter__(self) -> "Client": """Connect to the websocket.""" await self.connect() return self async def __aexit__( self, exc_type: Exception, exc_value: str, traceback: TracebackType ) -> None: """Disconnect from the websocket.""" await self.disconnect()
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/client.py
client.py
"""Firmware update helper.""" from __future__ import annotations import asyncio import aiohttp from .client import Client from .model.controller.firmware import ( ControllerFirmwareUpdateData, ControllerFirmwareUpdateResult, ) from .model.node import Node from .model.node.firmware import NodeFirmwareUpdateData, NodeFirmwareUpdateResult async def update_firmware( url: str, node: Node, updates: list[NodeFirmwareUpdateData], session: aiohttp.ClientSession, additional_user_agent_components: dict[str, str] | None = None, ) -> NodeFirmwareUpdateResult: """Send updateFirmware command to Node.""" client = Client( url, session, additional_user_agent_components=additional_user_agent_components ) await client.connect() await client.initialize() receive_task = asyncio.get_running_loop().create_task(client.receive_until_closed()) cmd = { "command": "node.update_firmware", "nodeId": node.node_id, "updates": [update.to_dict() for update in updates], } data = await client.async_send_command(cmd, require_schema=29) await client.disconnect() if not receive_task.done(): receive_task.cancel() return NodeFirmwareUpdateResult(node, data["result"]) async def controller_firmware_update_otw( url: str, firmware_file: ControllerFirmwareUpdateData, session: aiohttp.ClientSession, additional_user_agent_components: dict[str, str] | None = None, ) -> ControllerFirmwareUpdateResult: """ Send firmwareUpdateOTW command to Controller. Sending the wrong firmware to a controller can brick it and make it unrecoverable. Consumers of this library should build mechanisms to ensure that users understand the risks. """ client = Client( url, session, additional_user_agent_components=additional_user_agent_components ) await client.connect() await client.initialize() receive_task = asyncio.get_running_loop().create_task(client.receive_until_closed()) data = await client.async_send_command( { "command": "controller.firmware_update_otw", **firmware_file.to_dict(), }, require_schema=29, ) await client.disconnect() if not receive_task.done(): receive_task.cancel() return ControllerFirmwareUpdateResult(data["result"])
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/firmware.py
firmware.py
"""Version helper.""" from __future__ import annotations import aiohttp from .model.version import VersionInfo async def get_server_version(url: str, session: aiohttp.ClientSession) -> VersionInfo: """Return a server version.""" client = await session.ws_connect(url) try: return VersionInfo.from_message(await client.receive_json()) finally: await client.close()
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/version.py
version.py
"""Provide a package for zwave-js-server."""
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/__init__.py
__init__.py
"""Exceptions for zwave-js-server.""" from __future__ import annotations from typing import TYPE_CHECKING from .const import RssiError if TYPE_CHECKING: from .const import CommandClass from .model.value import Value from .model.version import VersionInfo class BaseZwaveJSServerError(Exception): """Base Zwave JS Server exception.""" class TransportError(BaseZwaveJSServerError): """Exception raised to represent transport errors.""" def __init__(self, message: str, error: Exception | None = None) -> None: """Initialize a transport error.""" super().__init__(message) self.error = error class ConnectionClosed(TransportError): """Exception raised when the connection is closed.""" class CannotConnect(TransportError): """Exception raised when failed to connect the client.""" def __init__(self, error: Exception) -> None: """Initialize a cannot connect error.""" super().__init__(f"{error}", error) class ConnectionFailed(TransportError): """Exception raised when an established connection fails.""" def __init__(self, error: Exception | None = None) -> None: """Initialize a connection failed error.""" if error is None: super().__init__("Connection failed.") return super().__init__(f"{error}", error) class NotFoundError(BaseZwaveJSServerError): """Exception that is raised when an entity can't be found.""" class NotConnected(BaseZwaveJSServerError): """Exception raised when not connected to client.""" class InvalidState(BaseZwaveJSServerError): """Exception raised when data gets in invalid state.""" class InvalidMessage(BaseZwaveJSServerError): """Exception raised when an invalid message is received.""" class InvalidServerVersion(BaseZwaveJSServerError): """Exception raised when connected to server with incompatible version.""" def __init__( self, version_info: "VersionInfo", required_schema_version: int, message: str, ) -> None: """Initialize an invalid server version error.""" self.server_version = version_info.server_version self.server_max_schema_version = version_info.max_schema_version self.required_schema_version = required_schema_version super().__init__(message) class FailedCommand(BaseZwaveJSServerError): """When a command has failed.""" def __init__( self, message_id: str, error_code: str, msg: str | None = None ) -> None: """Initialize a failed command error.""" super().__init__(msg or f"Command failed: {error_code}") self.message_id = message_id self.error_code = error_code class FailedZWaveCommand(FailedCommand): """When a command has failed because of Z-Wave JS error.""" def __init__( self, message_id: str, zwave_error_code: int, zwave_error_message: str ): """Initialize a failed command error.""" super().__init__( message_id, "zwave_error", f"Z-Wave error {zwave_error_code}: {zwave_error_message}", ) self.zwave_error_code = zwave_error_code self.zwave_error_message = zwave_error_message class UnparseableValue(BaseZwaveJSServerError): """Exception raised when a value can't be parsed.""" class UnwriteableValue(BaseZwaveJSServerError): """Exception raised when trying to change a read only Value.""" class InvalidNewValue(BaseZwaveJSServerError): """Exception raised when target new value is invalid based on Value metadata.""" class ValueTypeError(BaseZwaveJSServerError): """Exception raised when target Zwave value is the wrong type.""" class SetValueFailed(BaseZwaveJSServerError): """ Exception raise when setting a value fails. Refer to https://zwave-js.github.io/node-zwave-js/#/api/node?id=setvalue for possible reasons. """ class BulkSetConfigParameterFailed(BaseZwaveJSServerError): """ Exception raised when bulk setting a config parameter fails. Derived from another exception """ class InvalidCommandClass(BaseZwaveJSServerError): """Exception raised when Zwave Value has an invalid command class.""" def __init__(self, value: "Value", command_class: "CommandClass") -> None: """Initialize an invalid Command Class error.""" self.value = value self.command_class = command_class super().__init__( f"Value {value} does not match expected command class: {command_class}" ) class UnknownValueData(BaseZwaveJSServerError): """ Exception raised when Zwave Value has data that the library can't parse. This can be caused by an upstream issue with the driver, or missing support in the library. """ def __init__(self, value: "Value", path: str) -> None: """Initialize an unknown data error.""" self.value = value self.path = path super().__init__( f"Value {value} has unknown data in the following location: {path}. " f"A reinterview of node {value.node} may correct this issue, but if it " "doesn't, please report this issue as it may be caused by either an " "upstream issue with the driver or missing support for this data in the " "library" ) class RssiErrorReceived(BaseZwaveJSServerError): """Exception raised when an RSSI error is received.""" def __init__(self, error: "RssiError") -> None: """Initialize an RSSI error.""" self.error = error super().__init__() class RepeaterRssiErrorReceived(BaseZwaveJSServerError): """Exception raised when an RSSI error is received in list of RSSIs.""" def __init__(self, rssi_list: list[int]) -> None: """Initialize an RSSI error.""" self.rssi_list = rssi_list rssi_errors = [item.value for item in RssiError] self.error_list = [ RssiError(rssi_) if rssi_ in rssi_errors else None for rssi_ in rssi_list ] super().__init__()
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/exceptions.py
exceptions.py
"""Dump helper.""" from __future__ import annotations import asyncio import aiohttp from .client import INITIALIZE_MESSAGE_ID from .const import MAX_SERVER_SCHEMA_VERSION, PACKAGE_NAME, __version__ async def dump_msgs( url: str, session: aiohttp.ClientSession, additional_user_agent_components: dict[str, str] | None = None, timeout: float | None = None, ) -> list[dict]: """Dump server state.""" client = await session.ws_connect(url, compress=15, max_msg_size=0) msgs = [] version = await client.receive_json() msgs.append(version) for to_send in ( { "command": "initialize", "messageId": INITIALIZE_MESSAGE_ID, "schemaVersion": MAX_SERVER_SCHEMA_VERSION, "additionalUserAgentComponents": { PACKAGE_NAME: __version__, **(additional_user_agent_components or {}), }, }, {"command": "start_listening", "messageId": "start-listening"}, ): await client.send_json(to_send) msgs.append(await client.receive_json()) if timeout is None: await client.close() return msgs current_task = asyncio.current_task() assert current_task is not None asyncio.get_running_loop().call_later(timeout, current_task.cancel) while True: try: msg = await client.receive_json() msgs.append(msg) except asyncio.CancelledError: break await client.close() return msgs
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/dump.py
dump.py
"""Constants for the Z-Wave JS python library.""" from __future__ import annotations from dataclasses import dataclass, field from enum import Enum, IntEnum from importlib import metadata from typing import TypedDict PACKAGE_NAME = "zwave-js-server-python" __version__ = metadata.version(PACKAGE_NAME) # minimal server schema version we can handle MIN_SERVER_SCHEMA_VERSION = 31 # max server schema version we can handle (and our code is compatible with) MAX_SERVER_SCHEMA_VERSION = 31 VALUE_UNKNOWN = "unknown" NOT_INTERVIEWED = "None" INTERVIEW_FAILED = "Failed" CURRENT_STATE_PROPERTY = "currentState" TARGET_STATE_PROPERTY = "targetState" CURRENT_VALUE_PROPERTY = "currentValue" TARGET_VALUE_PROPERTY = "targetValue" DURATION_PROPERTY = "duration" TRANSITION_DURATION_OPTION = "transitionDuration" VOLUME_OPTION = "volume" class CommandStatus(str, Enum): """Status of a command sent to zwave-js-server.""" ACCEPTED = "accepted" QUEUED = "queued" # Multiple inheritance so that LogLevel will JSON serialize properly # Reference: https://stackoverflow.com/a/51976841 class LogLevel(str, Enum): """Enum for log levels used by node-zwave-js.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/log/shared.ts#L12 # https://github.com/winstonjs/triple-beam/blame/master/config/npm.js#L14 ERROR = "error" WARN = "warn" INFO = "info" HTTP = "http" VERBOSE = "verbose" DEBUG = "debug" SILLY = "silly" class CommandClass(IntEnum): """Enum with all known CommandClasses.""" SENSOR_ALARM = 156 SILENCE_ALARM = 157 SWITCH_ALL = 39 ANTITHEFT = 93 ANTITHEFT_UNLOCK = 126 APPLICATION_CAPABILITY = 87 APPLICATION_STATUS = 34 ASSOCIATION = 133 ASSOCIATION_COMMAND_CONFIGURATION = 155 ASSOCIATION_GRP_INFO = 89 AUTHENTICATION = 161 AUTHENTICATION_MEDIA_WRITE = 162 BARRIER_OPERATOR = 102 BASIC = 32 BASIC_TARIFF_INFO = 54 BASIC_WINDOW_COVERING = 80 BATTERY = 128 SENSOR_BINARY = 48 SWITCH_BINARY = 37 SWITCH_TOGGLE_BINARY = 40 CLIMATE_CONTROL_SCHEDULE = 70 CENTRAL_SCENE = 91 CLOCK = 129 SWITCH_COLOR = 51 CONFIGURATION = 112 CONTROLLER_REPLICATION = 33 CRC_16_ENCAP = 86 DCP_CONFIG = 58 DCP_MONITOR = 59 DEVICE_RESET_LOCALLY = 90 DOOR_LOCK = 98 DOOR_LOCK_LOGGING = 76 ENERGY_PRODUCTION = 144 ENTRY_CONTROL = 111 FIRMWARE_UPDATE_MD = 122 GENERIC_SCHEDULE = 163 GEOGRAPHIC_LOCATION = 140 GROUPING_NAME = 123 HAIL = 130 HRV_STATUS = 55 HRV_CONTROL = 57 HUMIDITY_CONTROL_MODE = 109 HUMIDITY_CONTROL_OPERATING_STATE = 110 HUMIDITY_CONTROL_SETPOINT = 100 INCLUSION_CONTROLLER = 116 INDICATOR = 135 IP_ASSOCIATION = 92 IP_CONFIGURATION = 154 IR_REPEATER = 160 IRRIGATION = 107 LANGUAGE = 137 LOCK = 118 MAILBOX = 105 MANUFACTURER_PROPRIETARY = 145 MANUFACTURER_SPECIFIC = 114 MARK = 239 METER = 50 METER_TBL_CONFIG = 60 METER_TBL_MONITOR = 61 METER_TBL_PUSH = 62 MTP_WINDOW_COVERING = 81 MULTI_CHANNEL = 96 MULTI_CHANNEL_ASSOCIATION = 142 MULTI_CMD = 143 SENSOR_MULTILEVEL = 49 SWITCH_MULTILEVEL = 38 SWITCH_TOGGLE_MULTILEVEL = 41 NETWORK_MANAGEMENT_BASIC = 77 NETWORK_MANAGEMENT_INCLUSION = 52 NETWORK_MANAGEMENT_INSTALLATION_MAINTENANCE = 103 NETWORK_MANAGEMENT_PRIMARY = 84 NETWORK_MANAGEMENT_PROXY = 82 NO_OPERATION = 0 NODE_NAMING = 119 NODE_PROVISIONING = 120 NOTIFICATION = 113 POWERLEVEL = 115 PREPAYMENT = 63 PREPAYMENT_ENCAPSULATION = 65 PROPRIETARY = 136 PROTECTION = 117 METER_PULSE = 53 RATE_TBL_CONFIG = 72 RATE_TBL_MONITOR = 73 REMOTE_ASSOCIATION_ACTIVATE = 124 REMOTE_ASSOCIATION = 125 SCENE_ACTIVATION = 43 SCENE_ACTUATOR_CONF = 44 SCENE_CONTROLLER_CONF = 45 SCHEDULE = 83 SCHEDULE_ENTRY_LOCK = 78 SCREEN_ATTRIBUTES = 147 SCREEN_MD = 146 SECURITY = 152 SECURITY_2 = 159 SECURITY_SCHEME0_MARK = 61696 SENSOR_CONFIGURATION = 158 SIMPLE_AV_CONTROL = 148 SOUND_SWITCH = 121 SUPERVISION = 108 TARIFF_CONFIG = 74 TARIFF_TBL_MONITOR = 75 THERMOSTAT_FAN_MODE = 68 THERMOSTAT_FAN_STATE = 69 THERMOSTAT_MODE = 64 THERMOSTAT_OPERATING_STATE = 66 THERMOSTAT_SETBACK = 71 THERMOSTAT_SETPOINT = 67 TIME = 138 TIME_PARAMETERS = 139 TRANSPORT_SERVICE = 85 USER_CODE = 99 VERSION = 134 WAKE_UP = 132 WINDOW_COVERING = 106 ZIP = 35 ZIP_6LOWPAN = 79 ZIP_GATEWAY = 95 ZIP_NAMING = 104 ZIP_ND = 88 ZIP_PORTAL = 97 ZWAVEPLUS_INFO = 94 class ProtocolVersion(IntEnum): """Protocol version.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/Types.ts#L149 UNKNOWN = 0 VERSION_2_0 = 1 VERSION_4_2X_OR_5_0X = 2 VERSION_4_5X_OR_6_0X = 3 class NodeStatus(IntEnum): """Enum with all Node status values.""" # https://zwave-js.github.io/node-zwave-js/#/api/node?id=status UNKNOWN = 0 ASLEEP = 1 AWAKE = 2 DEAD = 3 ALIVE = 4 class ConfigurationValueType(str, Enum): """Enum for configuration value types.""" BOOLEAN = "boolean" ENUMERATED = "enumerated" MANUAL_ENTRY = "manual_entry" RANGE = "range" UNDEFINED = "undefined" class NodeType(IntEnum): """Enum with all Node types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/capabilities/NodeInfo.ts#L151-L156 CONTROLLER = 0 END_NODE = 1 # Exclusion enums class ExclusionStrategy(IntEnum): """Enum with all exclusion strategies.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L49-L56 EXCLUDE_ONLY = 0 DISABLE_PROVISIONING_ENTRY = 1 UNPROVISION = 2 # Inclusion enums class InclusionStrategy(IntEnum): """Enum for all known inclusion strategies.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L9-L46 DEFAULT = 0 SMART_START = 1 INSECURE = 2 SECURITY_S0 = 3 SECURITY_S2 = 4 class SecurityClass(IntEnum): """Enum for all known security classes.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/security/SecurityClass.ts#L3-L17 NONE = -1 S2_UNAUTHENTICATED = 0 S2_AUTHENTICATED = 1 S2_ACCESS_CONTROL = 2 S0_LEGACY = 7 class QRCodeVersion(IntEnum): """Enum for all known QR Code versions.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/security/QR.ts#L43-L46 S2 = 0 SMART_START = 1 class Protocols(IntEnum): """Enum for all known protocols.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/capabilities/Protocols.ts#L1-L4 ZWAVE = 0 ZWAVE_LONG_RANGE = 1 # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/security/QR.ts#L41 MINIMUM_QR_STRING_LENGTH = 52 class ZwaveFeature(IntEnum): """Enum for all known Zwave features.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Features.ts#L4 SMART_START = 0 class PowerLevel(IntEnum): """Enum for all known power levels.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/PowerlevelCC.ts#L38 NORMAL_POWER = 0 DBM_MINUS_1 = 1 DBM_MINUS_2 = 2 DBM_MINUS_3 = 3 DBM_MINUS_4 = 4 DBM_MINUS_5 = 5 DBM_MINUS_6 = 6 DBM_MINUS_7 = 7 DBM_MINUS_8 = 8 DBM_MINUS_9 = 9 class InclusionState(IntEnum): """Enum for all known inclusion states.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L154 IDLE = 0 INCLUDING = 1 EXCLUDING = 2 BUSY = 3 SMART_START = 4 class RFRegion(IntEnum): """Enum for all known RF regions.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/serialapi/misc/SerialAPISetupMessages.ts#L41 EUROPE = 0 USA = 1 AUSTRALIA_AND_NEW_ZEALAND = 2 HONG_KONG = 3 INDIA = 5 ISRAEL = 6 RUSSIA = 7 CHINA = 8 USA_LONG_RANGE = 9 JAPAN = 32 KOREA = 33 UNKNOWN = 254 DEFAULT_EU = 255 class ProtocolDataRate(IntEnum): """Enum for all known protocol data rates.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/capabilities/Protocols.ts#L6 ZWAVE_9K6 = 1 ZWAVE_40K = 2 ZWAVE_100K = 3 LONG_RANGE_100K = 4 class RssiError(IntEnum): """Enum for all known RSSI errors.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/SendDataShared.ts#L79 NOT_AVAILABLE = 127 RECEIVER_SATURATED = 126 NO_SIGNAL_DETECTED = 125 class ProvisioningEntryStatus(IntEnum): """Enum for all known provisioning entry statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L136 ACTIVE = 0 INACTIVE = 1 class SecurityBootstrapFailure(IntEnum): """Enum with all security bootstrap failure reasons.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L16 USER_CANCELED = 0 NO_KEYS_CONFIGURED = 1 S2_NO_USER_CALLBACKS = 2 TIMEOUT = 3 PARAMETER_MISMATCH = 4 NODE_CANCELED = 5 S2_INCORRECT_PIN = 6 S2_WRONG_SECURITY_LEVEL = 7 UNKNOWN = 8 class SetValueStatus(IntEnum): """Enum for all known setValue statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/lib/API.ts#L83 # The device reports no support for this command NO_DEVICE_SUPPORT = 0 # The device has accepted the command and is working on it WORKING = 1 # The device has rejected the command FAIL = 2 # The endpoint specified in the value ID does not exist ENDPOINT_NOT_FOUND = 3 # The given CC or its API is not implemented (yet) or it has no `setValue` implementation NOT_IMPLEMENTED = 4 # The value to set (or a related value) is invalid INVALID_VALUE = 5 # The command was sent successfully, but it is unknown whether it was executed SUCCESS_UNSUPERVISED = 254 # The device has executed the command successfully SUCCESS = 255 SET_VALUE_SUCCESS = ( SetValueStatus.SUCCESS, SetValueStatus.SUCCESS_UNSUPERVISED, SetValueStatus.WORKING, ) class RemoveNodeReason(IntEnum): """Enum for all known reasons why a node was removed.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L266 # The node was excluded by the user or an inclusion controller EXCLUDED = 0 # The node was excluded by an inclusion controller PROXY_EXCLUDED = 1 # The node was removed using the "remove failed node" feature REMOVE_FAILED = 2 # The node was replaced using the "replace failed node" feature REPLACED = 3 # The node was replaced by an inclusion controller PROXY_REPLACED = 4 # The node was reset locally and was auto-removed RESET = 5 # SmartStart inclusion failed, and the node was auto-removed as a result. SMART_START_FAILED = 6 class Weekday(IntEnum): """Enum for all known weekdays.""" UNKNOWN = 0 MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 class DateAndTimeDataType(TypedDict, total=False): """Represent a date and time data type.""" hour: int minute: int weekday: int second: int year: int month: int day: int dstOffset: int standardOffset: int @dataclass class DateAndTime: """Represent a date and time.""" data: DateAndTimeDataType hour: int | None = field(init=False) minute: int | None = field(init=False) weekday: Weekday | None = field(default=None, init=False) second: int | None = field(init=False) year: int | None = field(init=False) month: int | None = field(init=False) day: int | None = field(init=False) dst_offset: int | None = field(init=False) standard_offset: int | None = field(init=False) def __post_init__(self) -> None: """Post initialization.""" self.hour = self.data.get("hour") self.minute = self.data.get("minute") if weekday := self.data.get("weekday"): self.weekday = Weekday(weekday) self.second = self.data.get("second") self.year = self.data.get("year") self.month = self.data.get("month") self.day = self.data.get("day") self.dst_offset = self.data.get("dstOffset") self.standard_offset = self.data.get("standardOffset") class ControllerStatus(IntEnum): """Enum for all known controller statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/consts/ControllerStatus.TS # The controller is ready to accept commands and transmit READY = 0 # The controller is unresponsive UNRESPONSIVE = 1 # The controller is unable to transmit JAMMED = 2
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/__init__.py
__init__.py
"""Constants for the Color Switch CC.""" from __future__ import annotations from enum import IntEnum class ColorComponent(IntEnum): """Enum with all (known/used) Color Switch CC colors.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/ColorSwitchCC.ts#L62 WARM_WHITE = 0 COLD_WHITE = 1 RED = 2 GREEN = 3 BLUE = 4 AMBER = 5 CYAN = 6 PURPLE = 7 INDEX = 8 # Keys for the Color Switch CC combined colors value # https://github.com/zwave-js/node-zwave-js/pull/1782 COLOR_SWITCH_COMBINED_RED = "red" COLOR_SWITCH_COMBINED_GREEN = "green" COLOR_SWITCH_COMBINED_BLUE = "blue" COLOR_SWITCH_COMBINED_AMBER = "amber" COLOR_SWITCH_COMBINED_CYAN = "cyan" COLOR_SWITCH_COMBINED_PURPLE = "purple" COLOR_SWITCH_COMBINED_WARM_WHITE = "warmWhite" COLOR_SWITCH_COMBINED_COLD_WHITE = "coldWhite" CURRENT_COLOR_PROPERTY = "currentColor" TARGET_COLOR_PROPERTY = "targetColor"
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/color_switch.py
color_switch.py
""" Constants for the Thermostat CCs. Includes Thermostat Fan Mode, Thermostat Fan State, Thermostat Mode, Thermostat Operating State, Thermostat Setback, and Thermostat Setpoint CCs. """ from __future__ import annotations from enum import IntEnum THERMOSTAT_MODE_PROPERTY = "mode" THERMOSTAT_SETPOINT_PROPERTY = "setpoint" THERMOSTAT_OPERATING_STATE_PROPERTY = "state" THERMOSTAT_CURRENT_TEMP_PROPERTY = "Air temperature" THERMOSTAT_HUMIDITY_PROPERTY = "Humidity" THERMOSTAT_FAN_MODE_PROPERTY = "mode" THERMOSTAT_FAN_OFF_PROPERTY = "off" THERMOSTAT_FAN_STATE_PROPERTY = "state" class ThermostatMode(IntEnum): """Enum with all (known/used) Z-Wave ThermostatModes.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/ThermostatModeCC.ts#L53-L70 OFF = 0 HEAT = 1 COOL = 2 AUTO = 3 AUXILIARY = 4 RESUME_ON = 5 FAN = 6 FURNACE = 7 DRY = 8 MOIST = 9 AUTO_CHANGE_OVER = 10 HEATING_ECON = 11 COOLING_ECON = 12 AWAY = 13 FULL_POWER = 15 MANUFACTURER_SPECIFIC = 31 class ThermostatOperatingState(IntEnum): """Enum with all (known/used) Z-Wave Thermostat OperatingStates.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/ThermostatOperatingStateCC.ts#L38-L51 IDLE = 0 HEATING = 1 COOLING = 2 FAN_ONLY = 3 PENDING_HEAT = 4 PENDING_COOL = 5 VENT_ECONOMIZER = 6 AUX_HEATING = 7 SECOND_STAGE_HEATING = 8 SECOND_STAGE_COOLING = 9 SECOND_STAGE_AUX_HEAT = 10 THIRD_STAGE_AUX_HEAT = 11 class ThermostatSetpointType(IntEnum): """ Enum with all (known/used) Z-Wave Thermostat Setpoint Types. Returns tuple of (property_key, property_key_name). """ # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/ThermostatSetpointCC.ts#L53-L66 NA = 0 HEATING = 1 COOLING = 2 FURNACE = 7 DRY_AIR = 8 MOIST_AIR = 9 AUTO_CHANGEOVER = 10 ENERGY_SAVE_HEATING = 11 ENERGY_SAVE_COOLING = 12 AWAY_HEATING = 13 AWAY_COOLING = 14 FULL_POWER = 15 THERMOSTAT_MODE_SETPOINT_MAP: dict[int, list[ThermostatSetpointType]] = { ThermostatMode.OFF: [], ThermostatMode.HEAT: [ThermostatSetpointType.HEATING], ThermostatMode.COOL: [ThermostatSetpointType.COOLING], ThermostatMode.AUTO: [ ThermostatSetpointType.HEATING, ThermostatSetpointType.COOLING, ], ThermostatMode.AUXILIARY: [ThermostatSetpointType.HEATING], ThermostatMode.FURNACE: [ThermostatSetpointType.FURNACE], ThermostatMode.DRY: [ThermostatSetpointType.DRY_AIR], ThermostatMode.MOIST: [ThermostatSetpointType.MOIST_AIR], ThermostatMode.AUTO_CHANGE_OVER: [ThermostatSetpointType.AUTO_CHANGEOVER], ThermostatMode.HEATING_ECON: [ThermostatSetpointType.ENERGY_SAVE_HEATING], ThermostatMode.COOLING_ECON: [ThermostatSetpointType.ENERGY_SAVE_COOLING], ThermostatMode.AWAY: [ ThermostatSetpointType.AWAY_HEATING, ThermostatSetpointType.AWAY_COOLING, ], ThermostatMode.FULL_POWER: [ThermostatSetpointType.FULL_POWER], }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/thermostat.py
thermostat.py
"""Constants for the Barrier Operator CC.""" from __future__ import annotations from enum import IntEnum NO_POSITION_SUFFIX = "(no position)" WINDOW_COVERING_OPEN_PROPERTY = "open" WINDOW_COVERING_CLOSE_PROPERTY = "close" class WindowCoveringPropertyKey(IntEnum): """Enum of all known Window Covering CC property keys.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/lib/_Types.ts#L1588 OUTBOUND_LEFT_NO_POSITION = 0 OUTBOUND_LEFT = 1 OUTBOUND_RIGHT_NO_POSITION = 2 OUTBOUND_RIGHT = 3 INBOUND_LEFT_NO_POSITION = 4 INBOUND_LEFT = 5 INBOUND_RIGHT_NO_POSITION = 6 INBOUND_RIGHT = 7 INBOUND_LEFT_RIGHT_NO_POSITION = 8 INBOUND_LEFT_RIGHT = 9 VERTICAL_SLATS_ANGLE_NO_POSITION = 10 VERTICAL_SLATS_ANGLE = 11 OUTBOUND_BOTTOM_NO_POSITION = 12 OUTBOUND_BOTTOM = 13 OUTBOUND_TOP_NO_POSITION = 14 OUTBOUND_TOP = 15 INBOUND_BOTTOM_NO_POSITION = 16 INBOUND_BOTTOM = 17 INBOUND_TOP_NO_POSITION = 18 INBOUND_TOP = 19 INBOUND_TOP_BOTTOM_NO_POSITION = 20 INBOUND_TOP_BOTTOM = 21 HORIZONTAL_SLATS_ANGLE_NO_POSITION = 22 HORIZONTAL_SLATS_ANGLE = 23 NO_POSITION_PROPERTY_KEYS = { WindowCoveringPropertyKey.OUTBOUND_LEFT_NO_POSITION, WindowCoveringPropertyKey.OUTBOUND_RIGHT_NO_POSITION, WindowCoveringPropertyKey.INBOUND_LEFT_NO_POSITION, WindowCoveringPropertyKey.INBOUND_RIGHT_NO_POSITION, WindowCoveringPropertyKey.INBOUND_LEFT_RIGHT_NO_POSITION, WindowCoveringPropertyKey.VERTICAL_SLATS_ANGLE_NO_POSITION, WindowCoveringPropertyKey.OUTBOUND_BOTTOM_NO_POSITION, WindowCoveringPropertyKey.OUTBOUND_TOP_NO_POSITION, WindowCoveringPropertyKey.INBOUND_BOTTOM_NO_POSITION, WindowCoveringPropertyKey.INBOUND_TOP_NO_POSITION, WindowCoveringPropertyKey.INBOUND_TOP_BOTTOM_NO_POSITION, WindowCoveringPropertyKey.HORIZONTAL_SLATS_ANGLE_NO_POSITION, } class SlatStates(IntEnum): """Enum with all (known/used) Z-Wave Slat States.""" CLOSED_1 = 0 OPEN = 50 CLOSED_2 = 99
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/window_covering.py
window_covering.py
"""Constants for the Multilevel Switch CC.""" from __future__ import annotations from enum import IntEnum SET_TO_PREVIOUS_VALUE = 255 COVER_OPEN_PROPERTY = "Open" COVER_UP_PROPERTY = "Up" COVER_ON_PROPERTY = "On" COVER_CLOSE_PROPERTY = "Close" COVER_DOWN_PROPERTY = "Down" COVER_OFF_PROPERTY = "Off" class CoverStates(IntEnum): """Enum with all (known/used) Z-Wave Cover States.""" CLOSED = 0 OPEN = 99 class MultilevelSwitchCommand(IntEnum): """Enum for known multilevel switch notifications.""" START_LEVEL_CHANGE = 4 STOP_LEVEL_CHANGE = 5
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/multilevel_switch.py
multilevel_switch.py
"""Constants for the Sound Switch CC.""" from __future__ import annotations from enum import IntEnum TONE_ID_PROPERTY = "toneId" DEFAULT_TONE_ID_PROPERTY = "defaultToneId" DEFAULT_VOLUME_PROPERTY = "defaultVolume" class ToneID(IntEnum): """Enum with all known Sound Switch CC tone IDs.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/SoundSwitchCC.ts#L71 OFF = 0 DEFAULT = 255
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/sound_switch.py
sound_switch.py
""" Constants for the Humidity Control CCs. Includes Humidity Control Mode, Humidity Control Operating State, and Humidity Control Setpoint CCs. """ from __future__ import annotations from enum import IntEnum HUMIDITY_CONTROL_MODE_PROPERTY = "mode" HUMIDITY_CONTROL_OPERATING_STATE_PROPERTY = "state" HUMIDITY_CONTROL_SETPOINT_PROPERTY = "setpoint" HUMIDITY_CONTROL_SETPOINT_SCALE_PROPERTY = "setpointScale" HUMIDITY_CONTROL_SUPPORTED_SETPOINT_TYPES_PROPERTY = "supportedSetpointTypes" class HumidityControlMode(IntEnum): """Enum with all (known/used) Z-Wave HumidityControlModes.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/HumidityControlModeCC.ts OFF = 0 HUMIDIFY = 1 DEHUMIDIFY = 2 AUTO = 3 class HumidityControlOperatingState(IntEnum): """Enum with all (known/used) Z-Wave Humidity Control OperatingStates.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/HumidityControlOperatingStateCC.ts IDLE = 0 HUMIDIFYING = 1 DEHUMIDIFYING = 2 class HumidityControlSetpointType(IntEnum): """ Enum with all (known/used) Z-Wave Humidity Control Setpoint Types. Returns tuple of (property_key, property_key_name). """ # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/HumidityControlSetpointCC.ts NA = 0 HUMIDIFIER = 1 DEHUMIDIFIER = 2 AUTO = 3 HUMIDITY_CONTROL_MODE_SETPOINT_MAP: dict[int, list[HumidityControlSetpointType]] = { HumidityControlMode.OFF: [], HumidityControlMode.HUMIDIFY: [HumidityControlSetpointType.HUMIDIFIER], HumidityControlMode.DEHUMIDIFY: [HumidityControlSetpointType.DEHUMIDIFIER], HumidityControlMode.AUTO: [ HumidityControlSetpointType.HUMIDIFIER, HumidityControlSetpointType.DEHUMIDIFIER, ], }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/humidity_control.py
humidity_control.py
"""Constants for Meter CC.""" from __future__ import annotations from enum import IntEnum VALUE_PROPERTY = "value" CC_SPECIFIC_SCALE = "scale" CC_SPECIFIC_METER_TYPE = "meterType" CC_SPECIFIC_RATE_TYPE = "rateType" RESET_METER_CC_API = "reset" # optional attributes when calling the Meter CC reset API. # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/MeterCC.ts#L873-L881 RESET_METER_OPTION_TARGET_VALUE = "targetValue" RESET_METER_OPTION_TYPE = "type" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/meters.json class MeterType(IntEnum): """Enum with all known meter types.""" ELECTRIC = 1 GAS = 2 WATER = 3 HEATING = 4 COOLING = 5 class MeterScaleType(IntEnum): """Common base class for meter scale enums.""" class ElectricScale(MeterScaleType): """Enum with all known electric meter scale values.""" KILOWATT_HOUR = 0 KILOVOLT_AMPERE_HOUR = 1 WATT = 2 PULSE_COUNT = 3 VOLT = 4 AMPERE = 5 POWER_FACTOR = 6 KILOVOLT_AMPERE_REACTIVE = 7 KILOVOLT_AMPERE_REACTIVE_HOUR = 8 class GasScale(MeterScaleType): """Enum with all known gas meter scale values.""" CUBIC_METER = 0 CUBIC_FEET = 1 PULSE_COUNT = 3 class WaterScale(MeterScaleType): """Enum with all known water meter scale values.""" CUBIC_METER = 0 CUBIC_FEET = 1 US_GALLON = 2 PULSE_COUNT = 3 class HeatingScale(MeterScaleType): """Enum with all known heating meter scale values.""" KILOWATT_HOUR = 0 CoolingScale = HeatingScale METER_TYPE_TO_SCALE_ENUM_MAP: dict[MeterType, type[MeterScaleType]] = { MeterType.ELECTRIC: ElectricScale, MeterType.GAS: GasScale, MeterType.WATER: WaterScale, MeterType.HEATING: HeatingScale, MeterType.COOLING: CoolingScale, } ENERGY_TOTAL_INCREASING_METER_TYPES: list[MeterScaleType] = [ ElectricScale.KILOWATT_HOUR, ElectricScale.KILOVOLT_AMPERE_HOUR, ElectricScale.KILOVOLT_AMPERE_REACTIVE_HOUR, HeatingScale.KILOWATT_HOUR, CoolingScale.KILOWATT_HOUR, ElectricScale.PULSE_COUNT, ] POWER_METER_TYPES: list[MeterScaleType] = [ ElectricScale.WATT, ElectricScale.KILOVOLT_AMPERE_REACTIVE, ] POWER_FACTOR_METER_TYPES: list[MeterScaleType] = [ElectricScale.POWER_FACTOR] VOLTAGE_METER_TYPES: list[MeterScaleType] = [ElectricScale.VOLT] CURRENT_METER_TYPES: list[MeterScaleType] = [ElectricScale.AMPERE] GAS_METER_TYPES: list[MeterScaleType] = [ GasScale.CUBIC_METER, GasScale.CUBIC_FEET, GasScale.PULSE_COUNT, ] WATER_METER_TYPES: list[MeterScaleType] = [ WaterScale.CUBIC_METER, WaterScale.CUBIC_FEET, WaterScale.US_GALLON, WaterScale.PULSE_COUNT, ] UNIT_KILOWATT_HOUR: list[MeterScaleType] = [ ElectricScale.KILOWATT_HOUR, HeatingScale.KILOWATT_HOUR, CoolingScale.KILOWATT_HOUR, ] UNIT_KILOVOLT_AMPERE_HOUR: list[MeterScaleType] = [ElectricScale.KILOVOLT_AMPERE_HOUR] UNIT_WATT: list[MeterScaleType] = [ElectricScale.WATT] UNIT_PULSE_COUNT: list[MeterScaleType] = [ ElectricScale.PULSE_COUNT, GasScale.PULSE_COUNT, WaterScale.PULSE_COUNT, ] UNIT_VOLT: list[MeterScaleType] = [ElectricScale.VOLT] UNIT_AMPERE: list[MeterScaleType] = [ElectricScale.AMPERE] UNIT_POWER_FACTOR: list[MeterScaleType] = [ElectricScale.POWER_FACTOR] UNIT_KILOVOLT_AMPERE_REACTIVE: list[MeterScaleType] = [ ElectricScale.KILOVOLT_AMPERE_REACTIVE ] UNIT_KILOVOLT_AMPERE_REACTIVE_HOUR: list[MeterScaleType] = [ ElectricScale.KILOVOLT_AMPERE_REACTIVE_HOUR ] UNIT_CUBIC_METER: list[MeterScaleType] = [GasScale.CUBIC_METER, WaterScale.CUBIC_METER] UNIT_CUBIC_FEET: list[MeterScaleType] = [GasScale.CUBIC_FEET, WaterScale.CUBIC_FEET] UNIT_US_GALLON: list[MeterScaleType] = [WaterScale.US_GALLON]
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/meter.py
meter.py
"""Constants for the Notification CC.""" from __future__ import annotations CC_SPECIFIC_NOTIFICATION_TYPE = "notificationType"
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/notification.py
notification.py
"""Constants for the Protection CC.""" from __future__ import annotations LOCAL_PROPERTY = "local" RF_PROPERTY = "rf"
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/protection.py
protection.py
"""Constants for the Barrier Operator CC.""" from __future__ import annotations from enum import IntEnum SIGNALING_STATE_PROPERTY = "signalingState" class BarrierEventSignalingSubsystemState(IntEnum): """Enum with all (known/used) Z-Wave Barrier Event Signaling Subsystem States.""" # https://github.com/zwave-js/node-zwave-js/blob/15e1b59f627bfad8bfae114bd774a14089c76683/packages/zwave-js/src/lib/commandclass/BarrierOperatorCC.ts#L46-L49 OFF = 0 ON = 255 class BarrierState(IntEnum): """Enum with all (known/used) Z-Wave Barrier States.""" # https://github.com/zwave-js/node-zwave-js/blob/15e1b59f627bfad8bfae114bd774a14089c76683/packages/zwave-js/src/lib/commandclass/BarrierOperatorCC.ts#L107-L113 CLOSED = 0 CLOSING = 252 STOPPED = 253 OPENING = 254 OPEN = 255
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/barrier_operator.py
barrier_operator.py
""" Constants for lock related CCs. Includes Door Lock and Lock CCs. """ from __future__ import annotations from enum import Enum, IntEnum from .. import CommandClass class DoorLockMode(IntEnum): """Enum with all (known/used) Z-Wave lock states for CommandClass.DOOR_LOCK.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/DoorLockCC.ts#L56-L65 UNSECURED = 0 UNSECURED_WITH_TIMEOUT = 1 INSIDE_UNSECURED = 2 INSIDE_UNSECURED_WITH_TIMEOUT = 3 OUTSIDE_UNSECURED = 4 OUTSIDE_UNSECURED_WITH_TIMEOUT = 5 UNKNOWN = 254 SECURED = 255 class OperationType(IntEnum): """Enum with all (known/used) Z-Wave lock operation types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/lib/_Types.ts#L496 CONSTANT = 1 TIMED = 2 DOOR_LOCK_CC_UNSECURED_MAP = { OperationType.CONSTANT: { DoorLockMode.UNSECURED, DoorLockMode.INSIDE_UNSECURED, DoorLockMode.OUTSIDE_UNSECURED, }, OperationType.TIMED: { DoorLockMode.UNSECURED_WITH_TIMEOUT, DoorLockMode.INSIDE_UNSECURED_WITH_TIMEOUT, DoorLockMode.OUTSIDE_UNSECURED_WITH_TIMEOUT, }, } class LatchStatus(str, Enum): """Enum with all (known/used) Z-Wave latch statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/cc/DoorLockCC.ts#L854 OPEN = "open" CLOSED = "closed" class BoltStatus(str, Enum): """Enum with all (known/used) Z-Wave bolt statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/cc/DoorLockCC.ts#L854 LOCKED = "locked" UNLOCKED = "unlocked" class DoorStatus(str, Enum): """Enum with all (known/used) Z-Wave door statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/cc/DoorLockCC.ts#L854 OPEN = "open" CLOSED = "closed" class CodeSlotStatus(IntEnum): """Enum with all (known/used) Z-Wave code slot statuses.""" AVAILABLE = 0 ENABLED = 1 DISABLED = 2 # Depending on the Command Class being used by the lock, the lock state is # different so we need a map to track it LOCK_CMD_CLASS_TO_LOCKED_STATE_MAP = { CommandClass.DOOR_LOCK: DoorLockMode.SECURED, CommandClass.LOCK: True, } # Door Lock CC value constants BOLT_STATUS_PROPERTY = "boltStatus" CURRENT_AUTO_RELOCK_TIME_PROPERTY = "autoRelockTime" CURRENT_BLOCK_TO_BLOCK_PROPERTY = "blockToBlock" CURRENT_HOLD_AND_RELEASE_TIME_PROPERTY = "holdAndReleaseTime" CURRENT_INSIDE_HANDLES_CAN_OPEN_DOOR_PROPERTY = "insideHandlesCanOpenDoor" CURRENT_LOCK_TIMEOUT_PROPERTY = "lockTimeout" CURRENT_MODE_PROPERTY = "currentMode" CURRENT_OPERATION_TYPE_PROPERTY = "operationType" CURRENT_OUTSIDE_HANDLES_CAN_OPEN_DOOR_PROPERTY = "outsideHandlesCanOpenDoor" CURRENT_TWIST_ASSIST_PROPERTY = "twistAssist" DOOR_STATUS_PROPERTY = "doorStatus" LATCH_STATUS_PROPERTY = "latchStatus" TARGET_MODE_PROPERTY = "targetMode" # Door Lock CC configuration constants TARGET_AUTO_RELOCK_TIME_PROPERTY = CURRENT_AUTO_RELOCK_TIME_PROPERTY TARGET_BLOCK_TO_BLOCK_PROPERTY = CURRENT_BLOCK_TO_BLOCK_PROPERTY TARGET_HOLD_AND_RELEASE_TIME_PROPERTY = CURRENT_HOLD_AND_RELEASE_TIME_PROPERTY TARGET_INSIDE_HANDLES_CAN_OPEN_DOOR_PROPERTY = "insideHandlesCanOpenDoorConfiguration" TARGET_LOCK_TIMEOUT_PROPERTY = "lockTimeoutConfiguration" TARGET_OPERATION_TYPE_PROPERTY = CURRENT_OPERATION_TYPE_PROPERTY TARGET_OUTSIDE_HANDLES_CAN_OPEN_DOOR_PROPERTY = "outsideHandlesCanOpenDoorConfiguration" TARGET_TWIST_ASSIST_PROPERTY = CURRENT_TWIST_ASSIST_PROPERTY # Lock CC constants LOCKED_PROPERTY = "locked" # User Code CC constants LOCK_USERCODE_PROPERTY = "userCode" LOCK_USERCODE_STATUS_PROPERTY = "userIdStatus" ATTR_CODE_SLOT = "code_slot" ATTR_IN_USE = "in_use" ATTR_NAME = "name" ATTR_USERCODE = "usercode" # Depending on the Command Class being used by the lock, the locked state property # is different so we need a map to track it LOCK_CMD_CLASS_TO_PROPERTY_MAP = { CommandClass.DOOR_LOCK: TARGET_MODE_PROPERTY, CommandClass.LOCK: LOCKED_PROPERTY, }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/lock.py
lock.py
"""Constants for the Power Level Command Class.""" from __future__ import annotations from enum import IntEnum class PowerLevelTestStatus(IntEnum): """Enum with all known power level test statuses.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/PowerlevelCC.ts#L52 FAILED = 0 SUCCESS = 1 IN_PROGRESS = 2
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/power_level.py
power_level.py
"""Constants for the Wake Up CC.""" from __future__ import annotations WAKE_UP_INTERVAL_PROPERTY = "wakeUpInterval" WAKE_UP_CONTROLLER_NODE_ID_PROPERTY = "controllerNodeId"
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/wake_up.py
wake_up.py
"""Constants for the Multilevel Sensor CC.""" # ----------------------------------------------------------------------------------- # # **BEGINNING OF AUTOGENERATED CONTENT** (TO ADD ADDITIONAL MANUAL CONTENT, LOOK FOR # # THE "END OF AUTOGENERATED CONTENT" COMMENT BLOCK AND ADD YOUR CODE BELOW IT) # # ----------------------------------------------------------------------------------- # from __future__ import annotations from enum import IntEnum CC_SPECIFIC_SCALE = "scale" CC_SPECIFIC_SENSOR_TYPE = "sensorType" class MultilevelSensorType(IntEnum): """Enum for known multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json ACCELERATION_X_AXIS = 52 ACCELERATION_Y_AXIS = 53 ACCELERATION_Z_AXIS = 54 AIR_FLOW = 18 AIR_TEMPERATURE = 1 AMMONIA = 84 ANGLE_POSITION = 21 APPLIED_FORCE_ON_THE_SENSOR = 71 ATMOSPHERIC_PRESSURE = 8 BAROMETRIC_PRESSURE = 9 BASIS_METABOLIC_RATE = 50 BLOOD_PRESSURE = 45 BODY_MASS_INDEX = 51 BOILER_WATER_TEMPERATURE = 62 BONE_MASS = 48 CARBON_DIOXIDE_LEVEL = 17 CARBON_MONOXIDE_LEVEL = 40 CONDENSER_COIL_TEMPERATURE = 74 CURRENT = 16 DEFROST_TEMPERATURE = 80 DEW_POINT = 11 DIRECTION = 7 DISCHARGE_LINE_TEMPERATURE = 77 DISCHARGE_PRESSURE = 79 DISTANCE = 20 DOMESTIC_HOT_WATER_TEMPERATURE = 63 ELECTRICAL_CONDUCTIVITY = 29 ELECTRICAL_RESISTIVITY = 28 EVAPORATOR_COIL_TEMPERATURE = 75 EXHAUST_TEMPERATURE = 65 FAT_MASS = 47 FORMALDEHYDE_LEVEL = 36 FREQUENCY = 32 GENERAL_PURPOSE = 2 HEART_RATE = 44 HEART_RATE_LF_HF_RATIO = 69 HUMIDITY = 5 ILLUMINANCE = 3 LEAD = 85 LIQUID_LINE_TEMPERATURE = 76 LOUDNESS = 30 METHANE_DENSITY = 38 MOISTURE = 31 MOTION_DIRECTION = 70 MUSCLE_MASS = 46 NITROGEN_DIOXIDE = 83 OUTSIDE_TEMPERATURE = 64 OZONE = 81 PARTICULATE_MATTER_1 = 86 PARTICULATE_MATTER_10 = 59 PARTICULATE_MATTER_2_5 = 35 PERSON_COUNTER_ENTERING = 87 PERSON_COUNTER_EXITING = 88 POWER = 4 RADON_CONCENTRATION = 37 RAIN_RATE = 12 RELATIVE_MODULATION_LEVEL = 61 RESPIRATORY_RATE = 60 RETURN_AIR_TEMPERATURE = 72 RF_SIGNAL_STRENGTH = 58 ROTATION = 22 SEISMIC_INTENSITY = 25 SEISMIC_MAGNITUDE = 26 SMOKE_DENSITY = 55 SOIL_HUMIDITY = 41 SOIL_REACTIVITY = 42 SOIL_SALINITY = 43 SOIL_TEMPERATURE = 24 SOLAR_RADIATION = 10 SUCTION_PRESSURE = 78 SULFUR_DIOXIDE = 82 SUPPLY_AIR_TEMPERATURE = 73 TANK_CAPACITY = 19 TARGET_TEMPERATURE = 34 TIDE_LEVEL = 13 TIME = 33 TOTAL_BODY_WATER = 49 ULTRAVIOLET = 27 VELOCITY = 6 VOLATILE_ORGANIC_COMPOUND_LEVEL = 39 VOLTAGE = 15 WATER_ACIDITY = 67 WATER_CHLORINE_LEVEL = 66 WATER_FLOW = 56 WATER_OXIDATION_REDUCTION_POTENTIAL = 68 WATER_PRESSURE = 57 WATER_TEMPERATURE = 23 WEIGHT = 14 class MultilevelSensorScaleType(IntEnum): """Common base class for multilevel sensor scale enums.""" class AirFlowScale(MultilevelSensorScaleType): """Enum for known scales for AIR_FLOW multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json CUBIC_FEET_PER_MINUTE = 1 CUBIC_METER_PER_HOUR = 0 class AnglePositionScale(MultilevelSensorScaleType): """Enum for known scales for ANGLE_POSITION multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json DEGREES_RELATIVE_TO_NORTH_POLE_OF_STANDING_EYE_VIEW = 1 DEGREES_RELATIVE_TO_SOUTH_POLE_OF_STANDING_EYE_VIEW = 2 PERCENTAGE_VALUE = 0 class AppliedForceOnTheSensorScale(MultilevelSensorScaleType): """Enum for known scales for APPLIED_FORCE_ON_THE_SENSOR multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json NEWTON = 0 class AccelerationScale(MultilevelSensorScaleType): """Enum for known scales for Acceleration multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json METER_PER_SQUARE_SECOND = 0 class AcidityScale(MultilevelSensorScaleType): """Enum for known scales for Acidity multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json ACIDITY = 0 class AirPressureScale(MultilevelSensorScaleType): """Enum for known scales for Air Pressure multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json INCHES_OF_MERCURY = 1 KILOPASCAL = 0 class BasisMetabolicRateScale(MultilevelSensorScaleType): """Enum for known scales for BASIS_METABOLIC_RATE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json JOULE = 0 class BloodPressureScale(MultilevelSensorScaleType): """Enum for known scales for BLOOD_PRESSURE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json DIASTOLIC = 1 SYSTOLIC = 0 class BodyMassIndexScale(MultilevelSensorScaleType): """Enum for known scales for BODY_MASS_INDEX multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BODY_MASS_INDEX = 0 class CarbonDioxideLevelScale(MultilevelSensorScaleType): """Enum for known scales for CARBON_DIOXIDE_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json PARTS_MILLION = 0 class CarbonMonoxideLevelScale(MultilevelSensorScaleType): """Enum for known scales for CARBON_MONOXIDE_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MOLE_PER_CUBIC_METER = 0 PARTS_MILLION = 1 class CurrentScale(MultilevelSensorScaleType): """Enum for known scales for CURRENT multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json AMPERE = 0 MILLIAMPERE = 1 class DistanceScale(MultilevelSensorScaleType): """Enum for known scales for DISTANCE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json CENTIMETER = 1 FEET = 2 METER = 0 class DensityScale(MultilevelSensorScaleType): """Enum for known scales for Density multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json DENSITY = 0 class DirectionScale(MultilevelSensorScaleType): """Enum for known scales for Direction multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json DEGREES = 0 class ElectricalConductivityScale(MultilevelSensorScaleType): """Enum for known scales for ELECTRICAL_CONDUCTIVITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json SIEMENS_PER_METER = 0 class ElectricalResistivityScale(MultilevelSensorScaleType): """Enum for known scales for ELECTRICAL_RESISTIVITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json OHM_METER = 0 class FormaldehydeLevelScale(MultilevelSensorScaleType): """Enum for known scales for FORMALDEHYDE_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MOLE_PER_CUBIC_METER = 0 class FrequencyScale(MultilevelSensorScaleType): """Enum for known scales for FREQUENCY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json HERTZ = 0 KILOHERTZ = 1 class GeneralPurposeScale(MultilevelSensorScaleType): """Enum for known scales for GENERAL_PURPOSE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json DIMENSIONLESS_VALUE = 1 PERCENTAGE_VALUE = 0 class HeartRateScale(MultilevelSensorScaleType): """Enum for known scales for HEART_RATE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BEATS_PER_MINUTE = 0 class HumidityScale(MultilevelSensorScaleType): """Enum for known scales for Humidity multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json ABSOLUTE_HUMIDITY = 1 PERCENTAGE_VALUE = 0 class IlluminanceScale(MultilevelSensorScaleType): """Enum for known scales for ILLUMINANCE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json LUX = 1 PERCENTAGE_VALUE = 0 class LoudnessScale(MultilevelSensorScaleType): """Enum for known scales for LOUDNESS multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json A_WEIGHTED_DECIBELS = 1 DECIBEL = 0 class MethaneDensityScale(MultilevelSensorScaleType): """Enum for known scales for METHANE_DENSITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MOLE_PER_CUBIC_METER = 0 class MoistureScale(MultilevelSensorScaleType): """Enum for known scales for MOISTURE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json IMPEDANCE = 2 PERCENTAGE_VALUE = 0 VOLUME_WATER_CONTENT = 1 WATER_ACTIVITY = 3 class MassScale(MultilevelSensorScaleType): """Enum for known scales for Mass multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json KILOGRAM = 0 class ParticulateMatter10Scale(MultilevelSensorScaleType): """Enum for known scales for PARTICULATE_MATTER_10 multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MICROGRAM_PER_CUBIC_METER = 1 MOLE_PER_CUBIC_METER = 0 class ParticulateMatter25Scale(MultilevelSensorScaleType): """Enum for known scales for PARTICULATE_MATTER_2_5 multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MICROGRAM_PER_CUBIC_METER = 1 MOLE_PER_CUBIC_METER = 0 class PowerScale(MultilevelSensorScaleType): """Enum for known scales for POWER multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BTU_H = 1 WATT = 0 class PercentageScale(MultilevelSensorScaleType): """Enum for known scales for Percentage multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json PERCENTAGE_VALUE = 0 class PressureScale(MultilevelSensorScaleType): """Enum for known scales for Pressure multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json KILOPASCAL = 0 POUND_PER_SQUARE_INCH = 1 class RadonConcentrationScale(MultilevelSensorScaleType): """Enum for known scales for RADON_CONCENTRATION multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BECQUEREL_PER_CUBIC_METER = 0 PICOCURIES_PER_LITER = 1 class RainRateScale(MultilevelSensorScaleType): """Enum for known scales for RAIN_RATE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json INCHES_PER_HOUR = 1 MILLIMETER_HOUR = 0 class RespiratoryRateScale(MultilevelSensorScaleType): """Enum for known scales for RESPIRATORY_RATE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BREATHS_PER_MINUTE = 0 class RfSignalStrengthScale(MultilevelSensorScaleType): """Enum for known scales for RF_SIGNAL_STRENGTH multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json POWER_LEVEL = 1 RSSI = 0 class RotationScale(MultilevelSensorScaleType): """Enum for known scales for ROTATION multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json HERTZ = 1 REVOLUTIONS_PER_MINUTE = 0 class SeismicIntensityScale(MultilevelSensorScaleType): """Enum for known scales for SEISMIC_INTENSITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json EUROPEAN_MACROSEISMIC = 1 LIEDU = 2 MERCALLI = 0 SHINDO = 3 class SeismicMagnitudeScale(MultilevelSensorScaleType): """Enum for known scales for SEISMIC_MAGNITUDE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json BODY_WAVE = 3 LOCAL = 0 MOMENT = 1 SURFACE_WAVE = 2 class SoilSalinityScale(MultilevelSensorScaleType): """Enum for known scales for SOIL_SALINITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MOLE_PER_CUBIC_METER = 0 class SolarRadiationScale(MultilevelSensorScaleType): """Enum for known scales for SOLAR_RADIATION multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json WATT_PER_SQUARE_METER = 0 class TankCapacityScale(MultilevelSensorScaleType): """Enum for known scales for TANK_CAPACITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json CUBIC_METER = 1 GALLONS = 2 LITER = 0 class TideLevelScale(MultilevelSensorScaleType): """Enum for known scales for TIDE_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json FEET = 1 METER = 0 class TimeScale(MultilevelSensorScaleType): """Enum for known scales for TIME multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json SECOND = 0 class TemperatureScale(MultilevelSensorScaleType): """Enum for known scales for Temperature multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json CELSIUS = 0 FAHRENHEIT = 1 class UltravioletScale(MultilevelSensorScaleType): """Enum for known scales for ULTRAVIOLET multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json UV_INDEX = 0 class UnitlessScale(MultilevelSensorScaleType): """Enum for known scales for Unitless multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json UNITLESS = 0 class VelocityScale(MultilevelSensorScaleType): """Enum for known scales for VELOCITY multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MPH = 1 M_S = 0 class VolatileOrganicCompoundLevelScale(MultilevelSensorScaleType): """Enum for known scales for VOLATILE_ORGANIC_COMPOUND_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MOLE_PER_CUBIC_METER = 0 PARTS_MILLION = 1 class VoltageScale(MultilevelSensorScaleType): """Enum for known scales for VOLTAGE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MILLIVOLT = 1 VOLT = 0 class WaterChlorineLevelScale(MultilevelSensorScaleType): """Enum for known scales for WATER_CHLORINE_LEVEL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MILLIGRAM_PER_LITER = 0 class WaterFlowScale(MultilevelSensorScaleType): """Enum for known scales for WATER_FLOW multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json LITER_PER_HOUR = 0 class WaterOxidationReductionPotentialScale(MultilevelSensorScaleType): """Enum for known scales for WATER_OXIDATION_REDUCTION_POTENTIAL multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json MILLIVOLT = 0 class WaterPressureScale(MultilevelSensorScaleType): """Enum for known scales for WATER_PRESSURE multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json KILOPASCAL = 0 class WeightScale(MultilevelSensorScaleType): """Enum for known scales for WEIGHT multilevel sensor types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/sensorTypes.json KILOGRAM = 0 POUNDS = 1 MULTILEVEL_SENSOR_TYPE_TO_SCALE_MAP: dict[ MultilevelSensorType, type[MultilevelSensorScaleType] ] = { MultilevelSensorType.ACCELERATION_X_AXIS: AccelerationScale, MultilevelSensorType.ACCELERATION_Y_AXIS: AccelerationScale, MultilevelSensorType.ACCELERATION_Z_AXIS: AccelerationScale, MultilevelSensorType.AIR_FLOW: AirFlowScale, MultilevelSensorType.AIR_TEMPERATURE: TemperatureScale, MultilevelSensorType.AMMONIA: DensityScale, MultilevelSensorType.ANGLE_POSITION: AnglePositionScale, MultilevelSensorType.APPLIED_FORCE_ON_THE_SENSOR: AppliedForceOnTheSensorScale, MultilevelSensorType.ATMOSPHERIC_PRESSURE: AirPressureScale, MultilevelSensorType.BAROMETRIC_PRESSURE: AirPressureScale, MultilevelSensorType.BASIS_METABOLIC_RATE: BasisMetabolicRateScale, MultilevelSensorType.BLOOD_PRESSURE: BloodPressureScale, MultilevelSensorType.BODY_MASS_INDEX: BodyMassIndexScale, MultilevelSensorType.BOILER_WATER_TEMPERATURE: TemperatureScale, MultilevelSensorType.BONE_MASS: MassScale, MultilevelSensorType.CARBON_DIOXIDE_LEVEL: CarbonDioxideLevelScale, MultilevelSensorType.CARBON_MONOXIDE_LEVEL: CarbonMonoxideLevelScale, MultilevelSensorType.CONDENSER_COIL_TEMPERATURE: TemperatureScale, MultilevelSensorType.CURRENT: CurrentScale, MultilevelSensorType.DEFROST_TEMPERATURE: TemperatureScale, MultilevelSensorType.DEW_POINT: TemperatureScale, MultilevelSensorType.DIRECTION: DirectionScale, MultilevelSensorType.DISCHARGE_LINE_TEMPERATURE: TemperatureScale, MultilevelSensorType.DISCHARGE_PRESSURE: PressureScale, MultilevelSensorType.DISTANCE: DistanceScale, MultilevelSensorType.DOMESTIC_HOT_WATER_TEMPERATURE: TemperatureScale, MultilevelSensorType.ELECTRICAL_CONDUCTIVITY: ElectricalConductivityScale, MultilevelSensorType.ELECTRICAL_RESISTIVITY: ElectricalResistivityScale, MultilevelSensorType.EVAPORATOR_COIL_TEMPERATURE: TemperatureScale, MultilevelSensorType.EXHAUST_TEMPERATURE: TemperatureScale, MultilevelSensorType.FAT_MASS: MassScale, MultilevelSensorType.FORMALDEHYDE_LEVEL: FormaldehydeLevelScale, MultilevelSensorType.FREQUENCY: FrequencyScale, MultilevelSensorType.GENERAL_PURPOSE: GeneralPurposeScale, MultilevelSensorType.HEART_RATE: HeartRateScale, MultilevelSensorType.HEART_RATE_LF_HF_RATIO: UnitlessScale, MultilevelSensorType.HUMIDITY: HumidityScale, MultilevelSensorType.ILLUMINANCE: IlluminanceScale, MultilevelSensorType.LEAD: DensityScale, MultilevelSensorType.LIQUID_LINE_TEMPERATURE: TemperatureScale, MultilevelSensorType.LOUDNESS: LoudnessScale, MultilevelSensorType.METHANE_DENSITY: MethaneDensityScale, MultilevelSensorType.MOISTURE: MoistureScale, MultilevelSensorType.MOTION_DIRECTION: DirectionScale, MultilevelSensorType.MUSCLE_MASS: MassScale, MultilevelSensorType.NITROGEN_DIOXIDE: DensityScale, MultilevelSensorType.OUTSIDE_TEMPERATURE: TemperatureScale, MultilevelSensorType.OZONE: DensityScale, MultilevelSensorType.PARTICULATE_MATTER_1: DensityScale, MultilevelSensorType.PARTICULATE_MATTER_10: ParticulateMatter10Scale, MultilevelSensorType.PARTICULATE_MATTER_2_5: ParticulateMatter25Scale, MultilevelSensorType.PERSON_COUNTER_ENTERING: UnitlessScale, MultilevelSensorType.PERSON_COUNTER_EXITING: UnitlessScale, MultilevelSensorType.POWER: PowerScale, MultilevelSensorType.RADON_CONCENTRATION: RadonConcentrationScale, MultilevelSensorType.RAIN_RATE: RainRateScale, MultilevelSensorType.RELATIVE_MODULATION_LEVEL: PercentageScale, MultilevelSensorType.RESPIRATORY_RATE: RespiratoryRateScale, MultilevelSensorType.RETURN_AIR_TEMPERATURE: TemperatureScale, MultilevelSensorType.RF_SIGNAL_STRENGTH: RfSignalStrengthScale, MultilevelSensorType.ROTATION: RotationScale, MultilevelSensorType.SEISMIC_INTENSITY: SeismicIntensityScale, MultilevelSensorType.SEISMIC_MAGNITUDE: SeismicMagnitudeScale, MultilevelSensorType.SMOKE_DENSITY: PercentageScale, MultilevelSensorType.SOIL_HUMIDITY: PercentageScale, MultilevelSensorType.SOIL_REACTIVITY: AcidityScale, MultilevelSensorType.SOIL_SALINITY: SoilSalinityScale, MultilevelSensorType.SOIL_TEMPERATURE: TemperatureScale, MultilevelSensorType.SOLAR_RADIATION: SolarRadiationScale, MultilevelSensorType.SUCTION_PRESSURE: PressureScale, MultilevelSensorType.SULFUR_DIOXIDE: DensityScale, MultilevelSensorType.SUPPLY_AIR_TEMPERATURE: TemperatureScale, MultilevelSensorType.TANK_CAPACITY: TankCapacityScale, MultilevelSensorType.TARGET_TEMPERATURE: TemperatureScale, MultilevelSensorType.TIDE_LEVEL: TideLevelScale, MultilevelSensorType.TIME: TimeScale, MultilevelSensorType.TOTAL_BODY_WATER: MassScale, MultilevelSensorType.ULTRAVIOLET: UltravioletScale, MultilevelSensorType.VELOCITY: VelocityScale, MultilevelSensorType.VOLATILE_ORGANIC_COMPOUND_LEVEL: VolatileOrganicCompoundLevelScale, MultilevelSensorType.VOLTAGE: VoltageScale, MultilevelSensorType.WATER_ACIDITY: AcidityScale, MultilevelSensorType.WATER_CHLORINE_LEVEL: WaterChlorineLevelScale, MultilevelSensorType.WATER_FLOW: WaterFlowScale, MultilevelSensorType.WATER_OXIDATION_REDUCTION_POTENTIAL: WaterOxidationReductionPotentialScale, MultilevelSensorType.WATER_PRESSURE: WaterPressureScale, MultilevelSensorType.WATER_TEMPERATURE: TemperatureScale, MultilevelSensorType.WEIGHT: WeightScale, } UNIT_ABSOLUTE_HUMIDITY: list[MultilevelSensorScaleType] = [ HumidityScale.ABSOLUTE_HUMIDITY ] UNIT_ACIDITY: list[MultilevelSensorScaleType] = [AcidityScale.ACIDITY] UNIT_AMPERE: list[MultilevelSensorScaleType] = [CurrentScale.AMPERE] UNIT_A_WEIGHTED_DECIBELS: list[MultilevelSensorScaleType] = [ LoudnessScale.A_WEIGHTED_DECIBELS ] UNIT_BEATS_PER_MINUTE: list[MultilevelSensorScaleType] = [ HeartRateScale.BEATS_PER_MINUTE ] UNIT_BECQUEREL_PER_CUBIC_METER: list[MultilevelSensorScaleType] = [ RadonConcentrationScale.BECQUEREL_PER_CUBIC_METER ] UNIT_BODY_MASS_INDEX: list[MultilevelSensorScaleType] = [ BodyMassIndexScale.BODY_MASS_INDEX ] UNIT_BODY_WAVE: list[MultilevelSensorScaleType] = [SeismicMagnitudeScale.BODY_WAVE] UNIT_BREATHS_PER_MINUTE: list[MultilevelSensorScaleType] = [ RespiratoryRateScale.BREATHS_PER_MINUTE ] UNIT_BTU_H: list[MultilevelSensorScaleType] = [PowerScale.BTU_H] UNIT_CELSIUS: list[MultilevelSensorScaleType] = [TemperatureScale.CELSIUS] UNIT_CENTIMETER: list[MultilevelSensorScaleType] = [DistanceScale.CENTIMETER] UNIT_CUBIC_FEET_PER_MINUTE: list[MultilevelSensorScaleType] = [ AirFlowScale.CUBIC_FEET_PER_MINUTE ] UNIT_CUBIC_METER: list[MultilevelSensorScaleType] = [TankCapacityScale.CUBIC_METER] UNIT_CUBIC_METER_PER_HOUR: list[MultilevelSensorScaleType] = [ AirFlowScale.CUBIC_METER_PER_HOUR ] UNIT_DECIBEL: list[MultilevelSensorScaleType] = [LoudnessScale.DECIBEL] UNIT_DEGREES: list[MultilevelSensorScaleType] = [DirectionScale.DEGREES] UNIT_DEGREES_RELATIVE_TO_NORTH_POLE_OF_STANDING_EYE_VIEW: list[ MultilevelSensorScaleType ] = [AnglePositionScale.DEGREES_RELATIVE_TO_NORTH_POLE_OF_STANDING_EYE_VIEW] UNIT_DEGREES_RELATIVE_TO_SOUTH_POLE_OF_STANDING_EYE_VIEW: list[ MultilevelSensorScaleType ] = [AnglePositionScale.DEGREES_RELATIVE_TO_SOUTH_POLE_OF_STANDING_EYE_VIEW] UNIT_DENSITY: list[MultilevelSensorScaleType] = [DensityScale.DENSITY] UNIT_DIASTOLIC: list[MultilevelSensorScaleType] = [BloodPressureScale.DIASTOLIC] UNIT_DIMENSIONLESS_VALUE: list[MultilevelSensorScaleType] = [ GeneralPurposeScale.DIMENSIONLESS_VALUE ] UNIT_EUROPEAN_MACROSEISMIC: list[MultilevelSensorScaleType] = [ SeismicIntensityScale.EUROPEAN_MACROSEISMIC ] UNIT_FAHRENHEIT: list[MultilevelSensorScaleType] = [TemperatureScale.FAHRENHEIT] UNIT_FEET: list[MultilevelSensorScaleType] = [DistanceScale.FEET, TideLevelScale.FEET] UNIT_GALLONS: list[MultilevelSensorScaleType] = [TankCapacityScale.GALLONS] UNIT_HERTZ: list[MultilevelSensorScaleType] = [ FrequencyScale.HERTZ, RotationScale.HERTZ, ] UNIT_IMPEDANCE: list[MultilevelSensorScaleType] = [MoistureScale.IMPEDANCE] UNIT_INCHES_OF_MERCURY: list[MultilevelSensorScaleType] = [ AirPressureScale.INCHES_OF_MERCURY ] UNIT_INCHES_PER_HOUR: list[MultilevelSensorScaleType] = [RainRateScale.INCHES_PER_HOUR] UNIT_JOULE: list[MultilevelSensorScaleType] = [BasisMetabolicRateScale.JOULE] UNIT_KILOGRAM: list[MultilevelSensorScaleType] = [ MassScale.KILOGRAM, WeightScale.KILOGRAM, ] UNIT_KILOHERTZ: list[MultilevelSensorScaleType] = [FrequencyScale.KILOHERTZ] UNIT_KILOPASCAL: list[MultilevelSensorScaleType] = [ AirPressureScale.KILOPASCAL, PressureScale.KILOPASCAL, WaterPressureScale.KILOPASCAL, ] UNIT_LIEDU: list[MultilevelSensorScaleType] = [SeismicIntensityScale.LIEDU] UNIT_LITER: list[MultilevelSensorScaleType] = [TankCapacityScale.LITER] UNIT_LITER_PER_HOUR: list[MultilevelSensorScaleType] = [WaterFlowScale.LITER_PER_HOUR] UNIT_LOCAL: list[MultilevelSensorScaleType] = [SeismicMagnitudeScale.LOCAL] UNIT_LUX: list[MultilevelSensorScaleType] = [IlluminanceScale.LUX] UNIT_MERCALLI: list[MultilevelSensorScaleType] = [SeismicIntensityScale.MERCALLI] UNIT_METER: list[MultilevelSensorScaleType] = [ DistanceScale.METER, TideLevelScale.METER, ] UNIT_METER_PER_SQUARE_SECOND: list[MultilevelSensorScaleType] = [ AccelerationScale.METER_PER_SQUARE_SECOND ] UNIT_MICROGRAM_PER_CUBIC_METER: list[MultilevelSensorScaleType] = [ ParticulateMatter10Scale.MICROGRAM_PER_CUBIC_METER, ParticulateMatter25Scale.MICROGRAM_PER_CUBIC_METER, ] UNIT_MILLIAMPERE: list[MultilevelSensorScaleType] = [CurrentScale.MILLIAMPERE] UNIT_MILLIGRAM_PER_LITER: list[MultilevelSensorScaleType] = [ WaterChlorineLevelScale.MILLIGRAM_PER_LITER ] UNIT_MILLIMETER_HOUR: list[MultilevelSensorScaleType] = [RainRateScale.MILLIMETER_HOUR] UNIT_MILLIVOLT: list[MultilevelSensorScaleType] = [ VoltageScale.MILLIVOLT, WaterOxidationReductionPotentialScale.MILLIVOLT, ] UNIT_MOLE_PER_CUBIC_METER: list[MultilevelSensorScaleType] = [ CarbonMonoxideLevelScale.MOLE_PER_CUBIC_METER, FormaldehydeLevelScale.MOLE_PER_CUBIC_METER, MethaneDensityScale.MOLE_PER_CUBIC_METER, ParticulateMatter10Scale.MOLE_PER_CUBIC_METER, ParticulateMatter25Scale.MOLE_PER_CUBIC_METER, SoilSalinityScale.MOLE_PER_CUBIC_METER, VolatileOrganicCompoundLevelScale.MOLE_PER_CUBIC_METER, ] UNIT_MOMENT: list[MultilevelSensorScaleType] = [SeismicMagnitudeScale.MOMENT] UNIT_MPH: list[MultilevelSensorScaleType] = [VelocityScale.MPH] UNIT_M_S: list[MultilevelSensorScaleType] = [VelocityScale.M_S] UNIT_NEWTON: list[MultilevelSensorScaleType] = [AppliedForceOnTheSensorScale.NEWTON] UNIT_OHM_METER: list[MultilevelSensorScaleType] = [ElectricalResistivityScale.OHM_METER] UNIT_PARTS_MILLION: list[MultilevelSensorScaleType] = [ CarbonDioxideLevelScale.PARTS_MILLION, CarbonMonoxideLevelScale.PARTS_MILLION, VolatileOrganicCompoundLevelScale.PARTS_MILLION, ] UNIT_PERCENTAGE_VALUE: list[MultilevelSensorScaleType] = [ AnglePositionScale.PERCENTAGE_VALUE, GeneralPurposeScale.PERCENTAGE_VALUE, HumidityScale.PERCENTAGE_VALUE, IlluminanceScale.PERCENTAGE_VALUE, MoistureScale.PERCENTAGE_VALUE, PercentageScale.PERCENTAGE_VALUE, ] UNIT_PICOCURIES_PER_LITER: list[MultilevelSensorScaleType] = [ RadonConcentrationScale.PICOCURIES_PER_LITER ] UNIT_POUNDS: list[MultilevelSensorScaleType] = [WeightScale.POUNDS] UNIT_POUND_PER_SQUARE_INCH: list[MultilevelSensorScaleType] = [ PressureScale.POUND_PER_SQUARE_INCH ] UNIT_POWER_LEVEL: list[MultilevelSensorScaleType] = [RfSignalStrengthScale.POWER_LEVEL] UNIT_REVOLUTIONS_PER_MINUTE: list[MultilevelSensorScaleType] = [ RotationScale.REVOLUTIONS_PER_MINUTE ] UNIT_RSSI: list[MultilevelSensorScaleType] = [RfSignalStrengthScale.RSSI] UNIT_SECOND: list[MultilevelSensorScaleType] = [TimeScale.SECOND] UNIT_SHINDO: list[MultilevelSensorScaleType] = [SeismicIntensityScale.SHINDO] UNIT_SIEMENS_PER_METER: list[MultilevelSensorScaleType] = [ ElectricalConductivityScale.SIEMENS_PER_METER ] UNIT_SURFACE_WAVE: list[MultilevelSensorScaleType] = [ SeismicMagnitudeScale.SURFACE_WAVE ] UNIT_SYSTOLIC: list[MultilevelSensorScaleType] = [BloodPressureScale.SYSTOLIC] UNIT_UNITLESS: list[MultilevelSensorScaleType] = [UnitlessScale.UNITLESS] UNIT_UV_INDEX: list[MultilevelSensorScaleType] = [UltravioletScale.UV_INDEX] UNIT_VOLT: list[MultilevelSensorScaleType] = [VoltageScale.VOLT] UNIT_VOLUME_WATER_CONTENT: list[MultilevelSensorScaleType] = [ MoistureScale.VOLUME_WATER_CONTENT ] UNIT_WATER_ACTIVITY: list[MultilevelSensorScaleType] = [MoistureScale.WATER_ACTIVITY] UNIT_WATT: list[MultilevelSensorScaleType] = [PowerScale.WATT] UNIT_WATT_PER_SQUARE_METER: list[MultilevelSensorScaleType] = [ SolarRadiationScale.WATT_PER_SQUARE_METER ] # ----------------------------------------------------------------------------------- # # **END OF AUTOGENERATED CONTENT** (DO NOT EDIT/REMOVE THIS COMMENT BLOCK AND DO NOT # # EDIT ANYTHING ABOVE IT. IF A NEW IMPORT IS NEEDED, UPDATE THE LINES AROUND 135 # # IN scripts/generate_multilevel_sensor_constants.py THEN RE-RUN THE SCRIPT. ALL # # LINES WRITTEN BELOW THIS BLOCK WILL BE PRESERVED AS LONG AS THIS BLOCK REMAINS) # # ----------------------------------------------------------------------------------- # CO_SENSORS = [MultilevelSensorType.CARBON_MONOXIDE_LEVEL] CO2_SENSORS = [MultilevelSensorType.CARBON_DIOXIDE_LEVEL] CURRENT_SENSORS = [MultilevelSensorType.CURRENT] ENERGY_MEASUREMENT_SENSORS = [MultilevelSensorType.BASIS_METABOLIC_RATE] HUMIDITY_SENSORS = [MultilevelSensorType.HUMIDITY] ILLUMINANCE_SENSORS = [MultilevelSensorType.ILLUMINANCE] POWER_SENSORS = [MultilevelSensorType.POWER] PRESSURE_SENSORS = [ MultilevelSensorType.BLOOD_PRESSURE, MultilevelSensorType.WATER_PRESSURE, MultilevelSensorType.SUCTION_PRESSURE, MultilevelSensorType.DISCHARGE_PRESSURE, MultilevelSensorType.BAROMETRIC_PRESSURE, MultilevelSensorType.ATMOSPHERIC_PRESSURE, ] SIGNAL_STRENGTH_SENSORS = [MultilevelSensorType.RF_SIGNAL_STRENGTH] TEMPERATURE_SENSORS = [ MultilevelSensorType.AIR_TEMPERATURE, MultilevelSensorType.DEW_POINT, MultilevelSensorType.WATER_TEMPERATURE, MultilevelSensorType.SOIL_TEMPERATURE, MultilevelSensorType.TARGET_TEMPERATURE, MultilevelSensorType.BOILER_WATER_TEMPERATURE, MultilevelSensorType.DOMESTIC_HOT_WATER_TEMPERATURE, MultilevelSensorType.OUTSIDE_TEMPERATURE, MultilevelSensorType.EXHAUST_TEMPERATURE, MultilevelSensorType.RETURN_AIR_TEMPERATURE, MultilevelSensorType.SUPPLY_AIR_TEMPERATURE, MultilevelSensorType.CONDENSER_COIL_TEMPERATURE, MultilevelSensorType.EVAPORATOR_COIL_TEMPERATURE, MultilevelSensorType.LIQUID_LINE_TEMPERATURE, MultilevelSensorType.DISCHARGE_LINE_TEMPERATURE, MultilevelSensorType.DEFROST_TEMPERATURE, ] VOLTAGE_SENSORS = [ MultilevelSensorType.VOLTAGE, MultilevelSensorType.WATER_OXIDATION_REDUCTION_POTENTIAL, ]
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/multilevel_sensor.py
multilevel_sensor.py
"""Constants for Command Classes."""
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/__init__.py
__init__.py
"""Constants for the Energy Production CC.""" from __future__ import annotations from enum import IntEnum class EnergyProductionParameter(IntEnum): """Energy Production CC parameter.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/lib/_Types.ts#L508 POWER = 0 TOTAL_PRODUCTION = 1 TODAYS_PRODUCTION = 2 TOTAL_TIME = 3 CC_SPECIFIC_PARAMETER = "parameter" CC_SPECIFIC_SCALE = "scale" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/cc/src/lib/_Types.ts#L520 class EnergyProductionScaleType(IntEnum): """Common base class for Energy Production scale enums.""" class PowerScale(EnergyProductionScaleType): """Enum with all known Energy Production power scale values.""" WATTS = 0 class TotalProductionScale(EnergyProductionScaleType): """Enum with all known Energy Production total production scale values.""" WATT_HOURS = 0 TodaysProductionScale = TotalProductionScale class TotalTimeScale(EnergyProductionScaleType): """Enum with all known Energy Production total time scale values.""" SECONDS = 0 HOURS = 1 ENERGY_PRODUCTION_PARAMETER_TO_SCALE_ENUM_MAP: dict[ EnergyProductionParameter, type[EnergyProductionScaleType] ] = { EnergyProductionParameter.POWER: PowerScale, EnergyProductionParameter.TOTAL_PRODUCTION: TotalProductionScale, EnergyProductionParameter.TODAYS_PRODUCTION: TodaysProductionScale, EnergyProductionParameter.TOTAL_TIME: TotalTimeScale, }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/energy_production.py
energy_production.py
"""Constants for the Entry Control CC.""" from __future__ import annotations from enum import IntEnum class EntryControlEventType(IntEnum): """Entry control event types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/EntryControlCC.ts#L54 CACHING = 0 CACHED_KEYS = 1 ENTER = 2 DISARM_ALL = 3 ARM_ALL = 4 ARM_AWAY = 5 ARM_HOME = 6 EXIT_DELAY = 7 ARM1 = 8 ARM2 = 9 ARM3 = 10 ARM4 = 11 ARM5 = 12 ARM6 = 13 RFID = 14 BELL = 15 FIRE = 16 POLICE = 17 ALERT_PANIC = 18 ALERT_MEDICAL = 19 GATE_OPEN = 20 GATE_CLOSE = 21 LOCK = 22 UNLOCK = 23 TEST = 24 CANCEL = 25 class EntryControlDataType(IntEnum): """Entry control data types.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/commandclass/EntryControlCC.ts#L83 NONE = 0 RAW = 1 ASCII = 2 MD5 = 3
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/const/command_class/entry_control.py
entry_control.py
"""Utility functions for Z-Wave JS nodes.""" from __future__ import annotations import logging from typing import cast from ..const import CommandClass, CommandStatus, ConfigurationValueType, SetValueStatus from ..exceptions import ( BulkSetConfigParameterFailed, InvalidNewValue, NotFoundError, SetValueFailed, ValueTypeError, ) from ..model.node import Node from ..model.value import ConfigurationValue, SetValueResult, get_value_id_str _LOGGER = logging.getLogger(__name__) def dump_node_state(node: Node) -> dict: """Get state from a node.""" return { **node.data, "values": {value_id: value.data for value_id, value in node.values.items()}, "endpoints": {idx: endpoint.data for idx, endpoint in node.endpoints.items()}, } def partial_param_bit_shift(property_key: int) -> int: """Get the number of bits to shift the value for a given property key.""" # We can get the binary representation of the property key, reverse it, # and find the first 1 return bin(property_key)[::-1].index("1") async def async_set_config_parameter( node: Node, new_value: int | str, property_or_property_name: int | str, property_key: int | str | None = None, endpoint: int = 0, ) -> tuple[ConfigurationValue, CommandStatus]: """ Set a value for a config parameter on this node. new_value and property_ can be provided as labels, so we need to resolve them to the appropriate key """ config_values = node.get_configuration_values() # If a property name is provided, we have to search for the correct value since # we can't use value ID if isinstance(property_or_property_name, str): try: zwave_value = next( config_value for config_value in config_values.values() if config_value.property_name == property_or_property_name and config_value.endpoint == endpoint ) except StopIteration: raise NotFoundError( "Configuration parameter with parameter name " f"{property_or_property_name} on node {node} endpoint {endpoint} " "could not be found" ) from None else: value_id = get_value_id_str( node, CommandClass.CONFIGURATION, property_or_property_name, endpoint=endpoint, property_key=property_key, ) if value_id not in config_values: raise NotFoundError( f"Configuration parameter with value ID {value_id} could not be " "found" ) from None zwave_value = config_values[value_id] new_value = _validate_and_transform_new_value(zwave_value, new_value) # Finally attempt to set the value and return the Value object if successful result = await node.async_set_value(zwave_value, new_value) if result and result.status not in ( SetValueStatus.WORKING, SetValueStatus.SUCCESS, SetValueStatus.SUCCESS_UNSUPERVISED, ): raise SetValueFailed(str(result)) status = CommandStatus.ACCEPTED if result is not None else CommandStatus.QUEUED return zwave_value, status async def async_bulk_set_partial_config_parameters( node: Node, property_: int, new_value: int | dict[int | str, int | str], endpoint: int = 0, ) -> CommandStatus: """Bulk set partial configuration values on this node.""" config_values = node.get_configuration_values() partial_param_values = { value_id: value for value_id, value in config_values.items() if value.property_ == property_ and value.endpoint == endpoint and value.property_key is not None } if not partial_param_values: # If we find a value with this property_, we know this value isn't split # into partial params if ( get_value_id_str( node, CommandClass.CONFIGURATION, property_, endpoint=endpoint ) in config_values ): # If the new value is provided as a dict, we don't have enough information # to set the parameter. if isinstance(new_value, dict): raise ValueTypeError( f"Configuration parameter {property_} for node {node.node_id} " f"endpoint {endpoint} does not have partials" ) # If the new value is provided as an int, we may as well try to set it # using the standard utility function _LOGGER.info( "Falling back to async_set_config_parameter because no partials " "were found" ) _, cmd_status = await async_set_config_parameter( node, new_value, property_, endpoint=endpoint ) return cmd_status # Otherwise if we can't find any values with this property, this config # parameter does not exist raise NotFoundError( f"Configuration parameter {property_} for node {node.node_id} endpoint " f"{endpoint} not found" ) # If new_value is a dictionary, we need to calculate the full value to send if isinstance(new_value, dict): new_value = _get_int_from_partials_dict( node, partial_param_values, property_, new_value, endpoint=endpoint ) else: _validate_raw_int(partial_param_values, new_value) cmd_response = await node.async_send_command( "set_value", valueId={ "commandClass": CommandClass.CONFIGURATION.value, "endpoint": endpoint, "property": property_, }, value=new_value, require_schema=29, ) # If we didn't wait for a response, we assume the command has been queued if cmd_response is None: return CommandStatus.QUEUED result = SetValueResult(cmd_response["result"]) if result.status not in ( SetValueStatus.WORKING, SetValueStatus.SUCCESS, SetValueStatus.SUCCESS_UNSUPERVISED, ): raise SetValueFailed(str(result)) return CommandStatus.ACCEPTED def _validate_and_transform_new_value( zwave_value: ConfigurationValue, new_value: int | str ) -> int: """Validate a new value and return the integer value to set.""" # If needed, convert a state label to its key. We know the state exists because # of the validation above. if isinstance(new_value, str): try: new_value = int( next( key for key, label in zwave_value.metadata.states.items() if label == new_value ) ) except StopIteration: raise InvalidNewValue( f"State '{new_value}' not found for parameter {zwave_value.value_id}" ) from None if zwave_value.configuration_value_type == ConfigurationValueType.UNDEFINED: # We need to use the Configuration CC API to set the value for this type raise NotImplementedError("Configuration values of undefined type can't be set") return new_value def _bulk_set_validate_and_transform_new_value( zwave_value: ConfigurationValue, property_key: int, new_partial_value: int | str ) -> int: """ Validate and transform new value for a bulk set function call. Returns a bulk set friendly error if validation fails. """ try: return _validate_and_transform_new_value(zwave_value, new_partial_value) except (InvalidNewValue, NotImplementedError) as err: raise BulkSetConfigParameterFailed( f"Config parameter {zwave_value.value_id} failed validation on partial " f"parameter {property_key}" ) from err def _get_int_from_partials_dict( node: Node, partial_param_values: dict[str, ConfigurationValue], property_: int, new_value: dict[int | str, int | str], endpoint: int = 0, ) -> int: """Take an input dict for a set of partial values and compute the raw int value.""" int_value = 0 provided_partial_values = [] # For each property key provided, we bit shift the partial value using the # property_key for property_key_or_name, partial_value in new_value.items(): # If the dict key is a property key, we can generate the value ID to find the # partial value if isinstance(property_key_or_name, int): value_id = get_value_id_str( node, CommandClass.CONFIGURATION, property_, property_key=property_key_or_name, endpoint=endpoint, ) if value_id not in partial_param_values: raise NotFoundError( f"Bitmask {property_key_or_name} ({hex(property_key_or_name)}) " f"not found for parameter {property_} on node {node} endpoint " f"{endpoint}" ) zwave_value = partial_param_values[value_id] # If the dict key is a property name, we have to find the value from the list # of partial param values else: try: zwave_value = next( value for value in partial_param_values.values() if value.property_name == property_key_or_name and value.endpoint == endpoint ) except StopIteration: raise NotFoundError( f"Partial parameter with label '{property_key_or_name}'" f"not found for parameter {property_} on node {node} endpoint " f"{endpoint}" ) from None provided_partial_values.append(zwave_value) property_key = cast(int, zwave_value.property_key) partial_value = _bulk_set_validate_and_transform_new_value( zwave_value, property_key, partial_value ) int_value += partial_value << partial_param_bit_shift(property_key) # To set partial parameters in bulk, we also have to include cached values for # property keys that haven't been specified missing_values = set(partial_param_values.values()) - set(provided_partial_values) int_value += sum( cast(int, property_value.value) << partial_param_bit_shift(cast(int, property_value.property_key)) for property_value in missing_values ) return int_value def _validate_raw_int( partial_param_values: dict[str, ConfigurationValue], new_value: int ) -> None: """ Validate raw value against all partial values. Raises if a partial value in the raw value is invalid. """ # Break down the bulk value into partial values and validate them against # each partial parameter's metadata by looping through the property values # starting with the highest property key for zwave_value in sorted( partial_param_values.values(), key=lambda val: cast(int, val.property_key), reverse=True, ): property_key = cast(int, zwave_value.property_key) multiplication_factor = 2 ** partial_param_bit_shift(property_key) partial_value = int(new_value / multiplication_factor) new_value = new_value % multiplication_factor _bulk_set_validate_and_transform_new_value( zwave_value, property_key, partial_value )
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/node.py
node.py