How to use uuid method in wpt

Best JavaScript code snippet using wpt

test_uuid.py

Source:test_uuid.py Github

copy

Full Screen

1from unittest import TestCase2from test import test_support3import uuid45def importable(name):6 try:7 __import__(name)8 return True9 except:10 return False1112class TestUUID(TestCase):13 last_node = None14 source2node = {}1516 def test_UUID(self):17 equal = self.assertEqual18 ascending = []19 for (string, curly, hex, bytes, bytes_le, fields, integer, urn,20 time, clock_seq, variant, version) in [21 ('00000000-0000-0000-0000-000000000000',22 '{00000000-0000-0000-0000-000000000000}',23 '00000000000000000000000000000000',24 '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',25 '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',26 (0, 0, 0, 0, 0, 0),27 0,28 'urn:uuid:00000000-0000-0000-0000-000000000000',29 0, 0, uuid.RESERVED_NCS, None),30 ('00010203-0405-0607-0809-0a0b0c0d0e0f',31 '{00010203-0405-0607-0809-0a0b0c0d0e0f}',32 '000102030405060708090a0b0c0d0e0f',33 '\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f',34 '\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f',35 (0x00010203L, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0fL),36 0x000102030405060708090a0b0c0d0e0fL,37 'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f',38 0x607040500010203L, 0x809, uuid.RESERVED_NCS, None),39 ('02d9e6d5-9467-382e-8f9b-9300a64ac3cd',40 '{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}',41 '02d9e6d59467382e8f9b9300a64ac3cd',42 '\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',43 '\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',44 (0x02d9e6d5L, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cdL),45 0x02d9e6d59467382e8f9b9300a64ac3cdL,46 'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd',47 0x82e946702d9e6d5L, 0xf9b, uuid.RFC_4122, 3),48 ('12345678-1234-5678-1234-567812345678',49 '{12345678-1234-5678-1234-567812345678}',50 '12345678123456781234567812345678',51 '\x12\x34\x56\x78'*4,52 '\x78\x56\x34\x12\x34\x12\x78\x56\x12\x34\x56\x78\x12\x34\x56\x78',53 (0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678),54 0x12345678123456781234567812345678,55 'urn:uuid:12345678-1234-5678-1234-567812345678',56 0x678123412345678L, 0x1234, uuid.RESERVED_NCS, None),57 ('6ba7b810-9dad-11d1-80b4-00c04fd430c8',58 '{6ba7b810-9dad-11d1-80b4-00c04fd430c8}',59 '6ba7b8109dad11d180b400c04fd430c8',60 '\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',61 '\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',62 (0x6ba7b810L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),63 0x6ba7b8109dad11d180b400c04fd430c8L,64 'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8',65 0x1d19dad6ba7b810L, 0xb4, uuid.RFC_4122, 1),66 ('6ba7b811-9dad-11d1-80b4-00c04fd430c8',67 '{6ba7b811-9dad-11d1-80b4-00c04fd430c8}',68 '6ba7b8119dad11d180b400c04fd430c8',69 '\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',70 '\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',71 (0x6ba7b811L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),72 0x6ba7b8119dad11d180b400c04fd430c8L,73 'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8',74 0x1d19dad6ba7b811L, 0xb4, uuid.RFC_4122, 1),75 ('6ba7b812-9dad-11d1-80b4-00c04fd430c8',76 '{6ba7b812-9dad-11d1-80b4-00c04fd430c8}',77 '6ba7b8129dad11d180b400c04fd430c8',78 '\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',79 '\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',80 (0x6ba7b812L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),81 0x6ba7b8129dad11d180b400c04fd430c8L,82 'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8',83 0x1d19dad6ba7b812L, 0xb4, uuid.RFC_4122, 1),84 ('6ba7b814-9dad-11d1-80b4-00c04fd430c8',85 '{6ba7b814-9dad-11d1-80b4-00c04fd430c8}',86 '6ba7b8149dad11d180b400c04fd430c8',87 '\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',88 '\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',89 (0x6ba7b814L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),90 0x6ba7b8149dad11d180b400c04fd430c8L,91 'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8',92 0x1d19dad6ba7b814L, 0xb4, uuid.RFC_4122, 1),93 ('7d444840-9dc0-11d1-b245-5ffdce74fad2',94 '{7d444840-9dc0-11d1-b245-5ffdce74fad2}',95 '7d4448409dc011d1b2455ffdce74fad2',96 '\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',97 '\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',98 (0x7d444840L, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2L),99 0x7d4448409dc011d1b2455ffdce74fad2L,100 'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2',101 0x1d19dc07d444840L, 0x3245, uuid.RFC_4122, 1),102 ('e902893a-9d22-3c7e-a7b8-d6e313b71d9f',103 '{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}',104 'e902893a9d223c7ea7b8d6e313b71d9f',105 '\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',106 '\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',107 (0xe902893aL, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9fL),108 0xe902893a9d223c7ea7b8d6e313b71d9fL,109 'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f',110 0xc7e9d22e902893aL, 0x27b8, uuid.RFC_4122, 3),111 ('eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',112 '{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}',113 'eb4240266f544ef8a4d0bb658a1fc6cf',114 '\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',115 '\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',116 (0xeb424026L, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cfL),117 0xeb4240266f544ef8a4d0bb658a1fc6cfL,118 'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',119 0xef86f54eb424026L, 0x24d0, uuid.RFC_4122, 4),120 ('f81d4fae-7dec-11d0-a765-00a0c91e6bf6',121 '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}',122 'f81d4fae7dec11d0a76500a0c91e6bf6',123 '\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',124 '\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',125 (0xf81d4faeL, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6L),126 0xf81d4fae7dec11d0a76500a0c91e6bf6L,127 'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6',128 0x1d07decf81d4faeL, 0x2765, uuid.RFC_4122, 1),129 ('fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',130 '{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}',131 'fffefdfcfffefffefffefffefdfcfbfa',132 '\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',133 '\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',134 (0xfffefdfcL, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfaL),135 0xfffefdfcfffefffefffefffefdfcfbfaL,136 'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',137 0xffefffefffefdfcL, 0x3ffe, uuid.RESERVED_FUTURE, None),138 ('ffffffff-ffff-ffff-ffff-ffffffffffff',139 '{ffffffff-ffff-ffff-ffff-ffffffffffff}',140 'ffffffffffffffffffffffffffffffff',141 '\xff'*16,142 '\xff'*16,143 (0xffffffffL, 0xffffL, 0xffffL, 0xff, 0xff, 0xffffffffffffL),144 0xffffffffffffffffffffffffffffffffL,145 'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff',146 0xfffffffffffffffL, 0x3fff, uuid.RESERVED_FUTURE, None),147 ]:148 equivalents = []149 # Construct each UUID in several different ways.150 for u in [uuid.UUID(string), uuid.UUID(curly), uuid.UUID(hex),151 uuid.UUID(bytes=bytes), uuid.UUID(bytes_le=bytes_le),152 uuid.UUID(fields=fields), uuid.UUID(int=integer),153 uuid.UUID(urn)]:154 # Test all conversions and properties of the UUID object.155 equal(str(u), string)156 equal(int(u), integer)157 equal(u.bytes, bytes)158 equal(u.bytes_le, bytes_le)159 equal(u.fields, fields)160 equal(u.time_low, fields[0])161 equal(u.time_mid, fields[1])162 equal(u.time_hi_version, fields[2])163 equal(u.clock_seq_hi_variant, fields[3])164 equal(u.clock_seq_low, fields[4])165 equal(u.node, fields[5])166 equal(u.hex, hex)167 equal(u.int, integer)168 equal(u.urn, urn)169 equal(u.time, time)170 equal(u.clock_seq, clock_seq)171 equal(u.variant, variant)172 equal(u.version, version)173 equivalents.append(u)174175 # Different construction methods should give the same UUID.176 for u in equivalents:177 for v in equivalents:178 equal(u, v)179 ascending.append(u)180181 # Test comparison of UUIDs.182 for i in range(len(ascending)):183 for j in range(len(ascending)):184 equal(cmp(i, j), cmp(ascending[i], ascending[j]))185186 # Test sorting of UUIDs (above list is in ascending order).187 resorted = ascending[:]188 resorted.reverse()189 resorted.sort()190 equal(ascending, resorted)191192 def test_exceptions(self):193 badvalue = lambda f: self.assertRaises(ValueError, f)194 badtype = lambda f: self.assertRaises(TypeError, f)195196 # Badly formed hex strings.197 badvalue(lambda: uuid.UUID(''))198 badvalue(lambda: uuid.UUID('abc'))199 badvalue(lambda: uuid.UUID('1234567812345678123456781234567'))200 badvalue(lambda: uuid.UUID('123456781234567812345678123456789'))201 badvalue(lambda: uuid.UUID('123456781234567812345678z2345678'))202203 # Badly formed bytes.204 badvalue(lambda: uuid.UUID(bytes='abc'))205 badvalue(lambda: uuid.UUID(bytes='\0'*15))206 badvalue(lambda: uuid.UUID(bytes='\0'*17))207208 # Badly formed bytes_le.209 badvalue(lambda: uuid.UUID(bytes_le='abc'))210 badvalue(lambda: uuid.UUID(bytes_le='\0'*15))211 badvalue(lambda: uuid.UUID(bytes_le='\0'*17))212213 # Badly formed fields.214 badvalue(lambda: uuid.UUID(fields=(1,)))215 badvalue(lambda: uuid.UUID(fields=(1, 2, 3, 4, 5)))216 badvalue(lambda: uuid.UUID(fields=(1, 2, 3, 4, 5, 6, 7)))217218 # Field values out of range.219 badvalue(lambda: uuid.UUID(fields=(-1, 0, 0, 0, 0, 0)))220 badvalue(lambda: uuid.UUID(fields=(0x100000000L, 0, 0, 0, 0, 0)))221 badvalue(lambda: uuid.UUID(fields=(0, -1, 0, 0, 0, 0)))222 badvalue(lambda: uuid.UUID(fields=(0, 0x10000L, 0, 0, 0, 0)))223 badvalue(lambda: uuid.UUID(fields=(0, 0, -1, 0, 0, 0)))224 badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000L, 0, 0, 0)))225 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, -1, 0, 0)))226 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100L, 0, 0)))227 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, -1, 0)))228 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100L, 0)))229 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, -1)))230 badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000L)))231232 # Version number out of range.233 badvalue(lambda: uuid.UUID('00'*16, version=0))234 badvalue(lambda: uuid.UUID('00'*16, version=6))235236 # Integer value out of range.237 badvalue(lambda: uuid.UUID(int=-1))238 badvalue(lambda: uuid.UUID(int=1<<128L))239240 # Must supply exactly one of hex, bytes, fields, int.241 h, b, f, i = '00'*16, '\0'*16, (0, 0, 0, 0, 0, 0), 0242 uuid.UUID(h)243 uuid.UUID(hex=h)244 uuid.UUID(bytes=b)245 uuid.UUID(bytes_le=b)246 uuid.UUID(fields=f)247 uuid.UUID(int=i)248249 # Wrong number of arguments (positional).250 badtype(lambda: uuid.UUID())251 badtype(lambda: uuid.UUID(h, b))252 badtype(lambda: uuid.UUID(h, b, b))253 badtype(lambda: uuid.UUID(h, b, b, f))254 badtype(lambda: uuid.UUID(h, b, b, f, i))255256 # Duplicate arguments.257 for hh in [[], [('hex', h)]]:258 for bb in [[], [('bytes', b)]]:259 for bble in [[], [('bytes_le', b)]]:260 for ii in [[], [('int', i)]]:261 for ff in [[], [('fields', f)]]:262 args = dict(hh + bb + bble + ii + ff)263 if len(args) != 0:264 badtype(lambda: uuid.UUID(h, **args))265 if len(args) != 1:266 badtype(lambda: uuid.UUID(**args))267268 # Immutability.269 u = uuid.UUID(h)270 badtype(lambda: setattr(u, 'hex', h))271 badtype(lambda: setattr(u, 'bytes', b))272 badtype(lambda: setattr(u, 'bytes_le', b))273 badtype(lambda: setattr(u, 'fields', f))274 badtype(lambda: setattr(u, 'int', i))275 badtype(lambda: setattr(u, 'time_low', 0))276 badtype(lambda: setattr(u, 'time_mid', 0))277 badtype(lambda: setattr(u, 'time_hi_version', 0))278 badtype(lambda: setattr(u, 'time_hi_version', 0))279 badtype(lambda: setattr(u, 'clock_seq_hi_variant', 0))280 badtype(lambda: setattr(u, 'clock_seq_low', 0))281 badtype(lambda: setattr(u, 'node', 0))282283 def check_node(self, node, source):284 individual_group_bit = (node >> 40L) & 1285 universal_local_bit = (node >> 40L) & 2286 message = "%012x doesn't look like a real MAC address" % node287 self.assertEqual(individual_group_bit, 0, message)288 self.assertEqual(universal_local_bit, 0, message)289 self.assertNotEqual(node, 0, message)290 self.assertNotEqual(node, 0xffffffffffffL, message)291 self.assert_(0 <= node, message)292 self.assert_(node < (1L << 48), message)293294 TestUUID.source2node[source] = node295 if TestUUID.last_node:296 if TestUUID.last_node != node:297 msg = "different sources disagree on node:\n"298 for s, n in TestUUID.source2node.iteritems():299 msg += " from source %r, node was %012x\n" % (s, n)300 # There's actually no reason to expect the MAC addresses301 # to agree across various methods -- e.g., a box may have302 # multiple network interfaces, and different ways of getting303 # a MAC address may favor different HW.304 ##self.fail(msg)305 else:306 TestUUID.last_node = node307308 def test_ifconfig_getnode(self):309 import sys310 print >>sys.__stdout__, \311""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.312 It is disabled until the code and/or test can be fixed properly."""313 return314315 import os316 if os.name == 'posix':317 node = uuid._ifconfig_getnode()318 if node is not None:319 self.check_node(node, 'ifconfig')320321 def test_ipconfig_getnode(self):322 import os323 if os.name == 'nt':324 node = uuid._ipconfig_getnode()325 if node is not None:326 self.check_node(node, 'ipconfig')327328 def test_netbios_getnode(self):329 if importable('win32wnet') and importable('netbios'):330 self.check_node(uuid._netbios_getnode(), 'netbios')331332 def test_random_getnode(self):333 node = uuid._random_getnode()334 self.assert_(0 <= node)335 self.assert_(node < (1L <<48))336337 def test_unixdll_getnode(self):338 import sys339 print >>sys.__stdout__, \340""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.341 It is disabled until the code and/or test can be fixed properly."""342 return343344 import os345 if importable('ctypes') and os.name == 'posix':346 self.check_node(uuid._unixdll_getnode(), 'unixdll')347348 def test_windll_getnode(self):349 import os350 if importable('ctypes') and os.name == 'nt':351 self.check_node(uuid._windll_getnode(), 'windll')352353 def test_getnode(self):354 import sys355 print >>sys.__stdout__, \356""" WARNING: uuid.getnode is unreliable on many platforms.357 It is disabled until the code and/or test can be fixed properly."""358 return359360 node1 = uuid.getnode()361 self.check_node(node1, "getnode1")362363 # Test it again to ensure consistency.364 node2 = uuid.getnode()365 self.check_node(node2, "getnode2")366367 self.assertEqual(node1, node2)368369 def test_uuid1(self):370 equal = self.assertEqual371372 # Make sure uuid1() generates UUIDs that are actually version 1.373 for u in [uuid.uuid1() for i in range(10)]:374 equal(u.variant, uuid.RFC_4122)375 equal(u.version, 1)376377 # Make sure the generated UUIDs are actually unique.378 uuids = {}379 for u in [uuid.uuid1() for i in range(1000)]:380 uuids[u] = 1381 equal(len(uuids.keys()), 1000)382383 # Make sure the supplied node ID appears in the UUID.384 u = uuid.uuid1(0)385 equal(u.node, 0)386 u = uuid.uuid1(0x123456789abc)387 equal(u.node, 0x123456789abc)388 u = uuid.uuid1(0xffffffffffff)389 equal(u.node, 0xffffffffffff)390391 # Make sure the supplied clock sequence appears in the UUID.392 u = uuid.uuid1(0x123456789abc, 0)393 equal(u.node, 0x123456789abc)394 equal(((u.clock_seq_hi_variant & 0x3f) << 8) | u.clock_seq_low, 0)395 u = uuid.uuid1(0x123456789abc, 0x1234)396 equal(u.node, 0x123456789abc)397 equal(((u.clock_seq_hi_variant & 0x3f) << 8) |398 u.clock_seq_low, 0x1234)399 u = uuid.uuid1(0x123456789abc, 0x3fff)400 equal(u.node, 0x123456789abc)401 equal(((u.clock_seq_hi_variant & 0x3f) << 8) |402 u.clock_seq_low, 0x3fff)403404 def test_uuid3(self):405 equal = self.assertEqual406407 # Test some known version-3 UUIDs.408 for u, v in [(uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org'),409 '6fa459ea-ee8a-3ca4-894e-db77e160355e'),410 (uuid.uuid3(uuid.NAMESPACE_URL, 'http://python.org/'),411 '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d'),412 (uuid.uuid3(uuid.NAMESPACE_OID, '1.3.6.1'),413 'dd1a1cef-13d5-368a-ad82-eca71acd4cd1'),414 (uuid.uuid3(uuid.NAMESPACE_X500, 'c=ca'),415 '658d3002-db6b-3040-a1d1-8ddd7d189a4d'),416 ]:417 equal(u.variant, uuid.RFC_4122)418 equal(u.version, 3)419 equal(u, uuid.UUID(v))420 equal(str(u), v)421422 def test_uuid4(self):423 equal = self.assertEqual424425 # Make sure uuid4() generates UUIDs that are actually version 4.426 for u in [uuid.uuid4() for i in range(10)]:427 equal(u.variant, uuid.RFC_4122)428 equal(u.version, 4)429430 # Make sure the generated UUIDs are actually unique.431 uuids = {}432 for u in [uuid.uuid4() for i in range(1000)]:433 uuids[u] = 1434 equal(len(uuids.keys()), 1000)435436 def test_uuid5(self):437 equal = self.assertEqual438439 # Test some known version-5 UUIDs.440 for u, v in [(uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org'),441 '886313e1-3b8a-5372-9b90-0c9aee199e5d'),442 (uuid.uuid5(uuid.NAMESPACE_URL, 'http://python.org/'),443 '4c565f0d-3f5a-5890-b41b-20cf47701c5e'),444 (uuid.uuid5(uuid.NAMESPACE_OID, '1.3.6.1'),445 '1447fa61-5277-5fef-a9b3-fbc6e44f4af3'),446 (uuid.uuid5(uuid.NAMESPACE_X500, 'c=ca'),447 'cc957dd1-a972-5349-98cd-874190002798'),448 ]:449 equal(u.variant, uuid.RFC_4122)450 equal(u.version, 5)451 equal(u, uuid.UUID(v))452 equal(str(u), v)453454455def test_main():456 test_support.run_unittest(TestUUID)457458if __name__ == '__main__': ...

Full Screen

Full Screen

noble.js

Source:noble.js Github

copy

Full Screen

1var debug = require('debug')('noble');2var events = require('events');3var util = require('util');4var Peripheral = require('./peripheral');5var Service = require('./service');6var Characteristic = require('./characteristic');7var Descriptor = require('./descriptor');8function Noble(bindings) {9 this.initialized = false;10 this.address = 'unknown';11 this._state = 'unknown';12 this._bindings = bindings;13 this._peripherals = {};14 this._services = {};15 this._characteristics = {};16 this._descriptors = {};17 this._discoveredPeripheralUUids = [];18 this._bindings.on('stateChange', this.onStateChange.bind(this));19 this._bindings.on('addressChange', this.onAddressChange.bind(this));20 this._bindings.on('scanStart', this.onScanStart.bind(this));21 this._bindings.on('scanStop', this.onScanStop.bind(this));22 this._bindings.on('discover', this.onDiscover.bind(this));23 this._bindings.on('connect', this.onConnect.bind(this));24 this._bindings.on('disconnect', this.onDisconnect.bind(this));25 this._bindings.on('rssiUpdate', this.onRssiUpdate.bind(this));26 this._bindings.on('servicesDiscover', this.onServicesDiscover.bind(this));27 this._bindings.on('includedServicesDiscover', this.onIncludedServicesDiscover.bind(this));28 this._bindings.on('characteristicsDiscover', this.onCharacteristicsDiscover.bind(this));29 this._bindings.on('read', this.onRead.bind(this));30 this._bindings.on('write', this.onWrite.bind(this));31 this._bindings.on('broadcast', this.onBroadcast.bind(this));32 this._bindings.on('notify', this.onNotify.bind(this));33 this._bindings.on('descriptorsDiscover', this.onDescriptorsDiscover.bind(this));34 this._bindings.on('valueRead', this.onValueRead.bind(this));35 this._bindings.on('valueWrite', this.onValueWrite.bind(this));36 this._bindings.on('handleRead', this.onHandleRead.bind(this));37 this._bindings.on('handleWrite', this.onHandleWrite.bind(this));38 this._bindings.on('handleNotify', this.onHandleNotify.bind(this));39 this.on('warning', function(message) {40 if (this.listeners('warning').length === 1) {41 console.warn('noble: ' + message);42 }43 }.bind(this));44 //lazy init bindings on first new listener, should be on stateChange45 this.on('newListener', function(event) {46 if (event === 'stateChange' && !this.initialized) {47 this.initialized = true;48 process.nextTick(function() {49 this._bindings.init();50 }.bind(this));51 }52 }.bind(this));53 //or lazy init bindings if someone attempts to get state first54 Object.defineProperties(this, {55 state: {56 get: function () {57 if (!this.initialized) {58 this.initialized = true;59 this._bindings.init();60 }61 return this._state;62 }63 }64 });65}66util.inherits(Noble, events.EventEmitter);67Noble.prototype.cancelLeConn = function() {68 this._bindings.cancelLeConn();69};70Noble.prototype.onStateChange = function(state) {71 debug('stateChange ' + state);72 this._state = state;73 this.emit('stateChange', state);74};75Noble.prototype.onAddressChange = function(address) {76 debug('addressChange ' + address);77 this.address = address;78};79Noble.prototype.startScanning = function(serviceUuids, allowDuplicates, callback) {80 var scan = function(state) {81 if (state !== 'poweredOn') {82 var error = new Error('Could not start scanning, state is ' + state + ' (not poweredOn)');83 if (typeof callback === 'function') {84 callback(error);85 } else {86 throw error;87 }88 } else {89 if (callback) {90 this.once('scanStart', function(filterDuplicates) {91 callback(null, filterDuplicates);92 });93 }94 this._discoveredPeripheralUUids = [];95 this._allowDuplicates = allowDuplicates;96 this._bindings.startScanning(serviceUuids, allowDuplicates);97 }98 };99 //if bindings still not init, do it now100 if (!this.initialized) {101 this.initialized = true;102 this._bindings.init();103 this.once('stateChange', scan.bind(this));104 }else{105 scan.call(this, this._state);106 }107};108Noble.prototype.onScanStart = function(filterDuplicates) {109 debug('scanStart');110 this.emit('scanStart', filterDuplicates);111};112Noble.prototype.stopScanning = function(callback) {113 if (callback) {114 this.once('scanStop', callback);115 }116 if (this._bindings && this.initialized) {117 this._bindings.stopScanning();118 }119};120Noble.prototype.onScanStop = function() {121 debug('scanStop');122 this.emit('scanStop');123};124Noble.prototype.onDiscover = function(uuid, address, addressType, connectable, advertisement, rssi) {125 return new Promise((resolve, reject) => {126 var peripheral = this._peripherals[uuid];127 if (!peripheral) {128 peripheral = new Peripheral(this, uuid, address, addressType, connectable, advertisement, rssi);129 this._peripherals[uuid] = peripheral;130 this._services[uuid] = {};131 this._characteristics[uuid] = {};132 this._descriptors[uuid] = {};133 } else {134 // "or" the advertisment data with existing135 for (var i in advertisement) {136 if (advertisement[i] !== undefined) {137 peripheral.advertisement[i] = advertisement[i];138 }139 }140 peripheral.connectable = connectable;141 peripheral.rssi = rssi;142 }143 var previouslyDiscoverd = (this._discoveredPeripheralUUids.indexOf(uuid) !== -1);144 if (!previouslyDiscoverd) {145 this._discoveredPeripheralUUids.push(uuid);146 }147 if (this._allowDuplicates || !previouslyDiscoverd) {148 this.emit('discover', peripheral);149 resolve(peripheral)150 }151 })152};153Noble.prototype.connect = function(peripheralUuid) {154 this._bindings.connect(peripheralUuid);155};156Noble.prototype.onConnect = function(peripheralUuid, error) {157 var peripheral = this._peripherals[peripheralUuid];158 if (peripheral) {159 peripheral.state = error ? 'error' : 'connected';160 peripheral.emit('connect', error);161 } else {162 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' connected!');163 }164};165Noble.prototype.disconnect = function(peripheralUuid) {166 this._bindings.disconnect(peripheralUuid);167};168Noble.prototype.onDisconnect = function(peripheralUuid) {169 var peripheral = this._peripherals[peripheralUuid];170 if (peripheral) {171 peripheral.state = 'disconnected';172 peripheral.emit('disconnect');173 } else {174 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' disconnected!');175 }176};177Noble.prototype.updateRssi = function(peripheralUuid) {178 this._bindings.updateRssi(peripheralUuid);179};180Noble.prototype.onRssiUpdate = function(peripheralUuid, rssi) {181 var peripheral = this._peripherals[peripheralUuid];182 if (peripheral) {183 peripheral.rssi = rssi;184 peripheral.emit('rssiUpdate', rssi);185 } else {186 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' RSSI update!');187 }188};189Noble.prototype.discoverServices = function(peripheralUuid, uuids) {190 this._bindings.discoverServices(peripheralUuid, uuids);191};192Noble.prototype.onServicesDiscover = function(peripheralUuid, serviceUuids) {193 var peripheral = this._peripherals[peripheralUuid];194 if (peripheral) {195 var services = [];196 for (var i = 0; i < serviceUuids.length; i++) {197 var serviceUuid = serviceUuids[i];198 var service = new Service(this, peripheralUuid, serviceUuid);199 this._services[peripheralUuid][serviceUuid] = service;200 if (typeof this._characteristics[peripheralUuid][serviceUuid] !== 'object') {201 this._characteristics[peripheralUuid][serviceUuid] = {};202 }203 if (typeof this._descriptors[peripheralUuid][serviceUuid] !== 'object') {204 this._descriptors[peripheralUuid][serviceUuid] = {};205 }206 services.push(service);207 }208 peripheral.services = services;209 peripheral.emit('servicesDiscover', services);210 } else {211 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' services discover!');212 }213};214Noble.prototype.discoverIncludedServices = function(peripheralUuid, serviceUuid, serviceUuids) {215 this._bindings.discoverIncludedServices(peripheralUuid, serviceUuid, serviceUuids);216};217Noble.prototype.onIncludedServicesDiscover = function(peripheralUuid, serviceUuid, includedServiceUuids) {218 var service = this._services[peripheralUuid][serviceUuid];219 if (service) {220 service.includedServiceUuids = includedServiceUuids;221 service.emit('includedServicesDiscover', includedServiceUuids);222 } else {223 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ' included services discover!');224 }225};226Noble.prototype.discoverCharacteristics = function(peripheralUuid, serviceUuid, characteristicUuids) {227 this._bindings.discoverCharacteristics(peripheralUuid, serviceUuid, characteristicUuids);228};229Noble.prototype.onCharacteristicsDiscover = function(peripheralUuid, serviceUuid, characteristics) {230 var service = this._services[peripheralUuid][serviceUuid];231 if (service) {232 var characteristics_ = [];233 for (var i = 0; i < characteristics.length; i++) {234 var characteristicUuid = characteristics[i].uuid;235 var characteristic = new Characteristic(236 this,237 peripheralUuid,238 serviceUuid,239 characteristicUuid,240 characteristics[i].properties241 );242 this._characteristics[peripheralUuid][serviceUuid][characteristicUuid] = characteristic;243 if (typeof this._descriptors[peripheralUuid][serviceUuid][characteristicUuid] !== 'object') {244 this._descriptors[peripheralUuid][serviceUuid][characteristicUuid] = {};245 }246 characteristics_.push(characteristic);247 }248 service.characteristics = characteristics_;249 service.emit('characteristicsDiscover', characteristics_);250 } else {251 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ' characteristics discover!');252 }253};254Noble.prototype.read = function(peripheralUuid, serviceUuid, characteristicUuid) {255 this._bindings.read(peripheralUuid, serviceUuid, characteristicUuid);256};257Noble.prototype.onRead = function(peripheralUuid, serviceUuid, characteristicUuid, data, isNotification) {258 var characteristic = this._characteristics[peripheralUuid][serviceUuid][characteristicUuid];259 if (characteristic) {260 characteristic.emit('data', data, isNotification);261 characteristic.emit('read', data, isNotification); // for backwards compatbility262 } else {263 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ' read!');264 }265};266Noble.prototype.write = function(peripheralUuid, serviceUuid, characteristicUuid, data, withoutResponse) {267 this._bindings.write(peripheralUuid, serviceUuid, characteristicUuid, data, withoutResponse);268};269Noble.prototype.onWrite = function(peripheralUuid, serviceUuid, characteristicUuid) {270 var characteristic = this._characteristics[peripheralUuid][serviceUuid][characteristicUuid];271 if (characteristic) {272 characteristic.emit('write');273 } else {274 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ' write!');275 }276};277Noble.prototype.broadcast = function(peripheralUuid, serviceUuid, characteristicUuid, broadcast) {278 this._bindings.broadcast(peripheralUuid, serviceUuid, characteristicUuid, broadcast);279};280Noble.prototype.onBroadcast = function(peripheralUuid, serviceUuid, characteristicUuid, state) {281 var characteristic = this._characteristics[peripheralUuid][serviceUuid][characteristicUuid];282 if (characteristic) {283 characteristic.emit('broadcast', state);284 } else {285 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ' broadcast!');286 }287};288Noble.prototype.notify = function(peripheralUuid, serviceUuid, characteristicUuid, notify) {289 this._bindings.notify(peripheralUuid, serviceUuid, characteristicUuid, notify);290};291Noble.prototype.onNotify = function(peripheralUuid, serviceUuid, characteristicUuid, state) {292 var characteristic = this._characteristics[peripheralUuid][serviceUuid][characteristicUuid];293 if (characteristic) {294 characteristic.emit('notify', state);295 } else {296 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ' notify!');297 }298};299Noble.prototype.discoverDescriptors = function(peripheralUuid, serviceUuid, characteristicUuid) {300 this._bindings.discoverDescriptors(peripheralUuid, serviceUuid, characteristicUuid);301};302Noble.prototype.onDescriptorsDiscover = function(peripheralUuid, serviceUuid, characteristicUuid, descriptors) {303 var characteristic = this._characteristics[peripheralUuid][serviceUuid][characteristicUuid];304 if (characteristic) {305 var descriptors_ = [];306 for (var i = 0; i < descriptors.length; i++) {307 var descriptorUuid = descriptors[i];308 var descriptor = new Descriptor(309 this,310 peripheralUuid,311 serviceUuid,312 characteristicUuid,313 descriptorUuid314 );315 this._descriptors[peripheralUuid][serviceUuid][characteristicUuid][descriptorUuid] = descriptor;316 descriptors_.push(descriptor);317 }318 characteristic.descriptors = descriptors_;319 characteristic.emit('descriptorsDiscover', descriptors_);320 } else {321 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ' descriptors discover!');322 }323};324Noble.prototype.readValue = function(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid) {325 this._bindings.readValue(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid);326};327Noble.prototype.onValueRead = function(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid, data) {328 var descriptor = this._descriptors[peripheralUuid][serviceUuid][characteristicUuid][descriptorUuid];329 if (descriptor) {330 descriptor.emit('valueRead', data);331 } else {332 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ', ' + descriptorUuid + ' value read!');333 }334};335Noble.prototype.writeValue = function(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid, data) {336 this._bindings.writeValue(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid, data);337};338Noble.prototype.onValueWrite = function(peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid) {339 var descriptor = this._descriptors[peripheralUuid][serviceUuid][characteristicUuid][descriptorUuid];340 if (descriptor) {341 descriptor.emit('valueWrite');342 } else {343 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ', ' + serviceUuid + ', ' + characteristicUuid + ', ' + descriptorUuid + ' value write!');344 }345};346Noble.prototype.readHandle = function(peripheralUuid, handle) {347 this._bindings.readHandle(peripheralUuid, handle);348};349Noble.prototype.onHandleRead = function(peripheralUuid, handle, data) {350 var peripheral = this._peripherals[peripheralUuid];351 if (peripheral) {352 peripheral.emit('handleRead' + handle, data);353 } else {354 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' handle read!');355 }356};357Noble.prototype.writeHandle = function(peripheralUuid, handle, data, withoutResponse) {358 this._bindings.writeHandle(peripheralUuid, handle, data, withoutResponse);359};360Noble.prototype.onHandleWrite = function(peripheralUuid, handle) {361 var peripheral = this._peripherals[peripheralUuid];362 if (peripheral) {363 peripheral.emit('handleWrite' + handle);364 } else {365 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' handle write!');366 }367};368Noble.prototype.onHandleNotify = function(peripheralUuid, handle, data) {369 var peripheral = this._peripherals[peripheralUuid];370 if (peripheral) {371 peripheral.emit('handleNotify', handle, data);372 } else {373 this.emit('warning', 'unknown peripheral ' + peripheralUuid + ' handle notify!');374 }375};...

Full Screen

Full Screen

bindings.js

Source:bindings.js Github

copy

Full Screen

1var events = require('events');2var util = require('util');3var debug = require('debug')('bindings');4var WebSocket = require('ws');5var NobleBindings = function() {6 var port = 0xB1e;7 this._ws = new WebSocket('ws://localhost:' + port);8 this._startScanCommand = null;9 this._peripherals = {};10 this.on('message', this._onMessage.bind(this));11 if (!this._ws.on) {12 this._ws.on = this._ws.addEventListener;13 }14 this._ws.on('open', this._onOpen.bind(this));15 this._ws.on('close', this._onClose.bind(this));16 this._ws.on('error', this._onClose.bind(this));17 var _this = this;18 this._ws.on('message', function(event) {19 var data = (process.title === 'browser') ? event.data : event;20 _this.emit('message', JSON.parse(data));21 });22};23util.inherits(NobleBindings, events.EventEmitter);24NobleBindings.prototype.init = function() {25 // no-op26};27NobleBindings.prototype._onOpen = function() {28 console.log('on -> open');29};30NobleBindings.prototype._onClose = function() {31 console.log('on -> close');32 this.emit('stateChange', 'poweredOff');33};34NobleBindings.prototype._onMessage = function(event) {35 var type = event.type;36 var peripheralUuid = event.peripheralUuid;37 var address = event.address;38 var addressType = event.addressType;39 var connectable = event.connectable;40 var advertisement = event.advertisement;41 var rssi = event.rssi;42 var serviceUuids = event.serviceUuids;43 var serviceUuid = event.serviceUuid;44 var includedServiceUuids = event.includedServiceUuids;45 var characteristics = event.characteristics;46 var characteristicUuid = event.characteristicUuid;47 var data = event.data ? new Buffer(event.data, 'hex') : null;48 var isNotification = event.isNotification;49 var state = event.state;50 var descriptors = event.descriptors;51 var descriptorUuid = event.descriptorUuid;52 var handle = event.handle;53 if (type === 'stateChange') {54 console.log(state);55 this.emit('stateChange', state);56 } else if (type === 'discover') {57 advertisement = {58 localName: advertisement.localName,59 txPowerLevel: advertisement.txPowerLevel,60 serviceUuids: advertisement.serviceUuids,61 manufacturerData: (advertisement.manufacturerData ? new Buffer(advertisement.manufacturerData, 'hex') : null),62 serviceData: (advertisement.serviceData ? new Buffer(advertisement.serviceData, 'hex') : null)63 };64 this._peripherals[peripheralUuid] = {65 uuid: peripheralUuid,66 address: address,67 advertisement: advertisement,68 rssi: rssi69 };70 this.emit('discover', peripheralUuid, address, addressType, connectable, advertisement, rssi);71 } else if (type === 'connect') {72 this.emit('connect', peripheralUuid);73 } else if (type === 'disconnect') {74 this.emit('disconnect', peripheralUuid);75 } else if (type === 'rssiUpdate') {76 this.emit('rssiUpdate', peripheralUuid, rssi);77 } else if (type === 'servicesDiscover') {78 this.emit('servicesDiscover', peripheralUuid, serviceUuids);79 } else if (type === 'includedServicesDiscover') {80 this.emit('includedServicesDiscover', peripheralUuid, serviceUuid, includedServiceUuids);81 } else if (type === 'characteristicsDiscover') {82 this.emit('characteristicsDiscover', peripheralUuid, serviceUuid, characteristics);83 } else if (type === 'read') {84 this.emit('read', peripheralUuid, serviceUuid, characteristicUuid, data, isNotification);85 } else if (type === 'write') {86 this.emit('write', peripheralUuid, serviceUuid, characteristicUuid);87 } else if (type === 'broadcast') {88 this.emit('broadcast', peripheralUuid, serviceUuid, characteristicUuid, state);89 } else if (type === 'notify') {90 this.emit('notify', peripheralUuid, serviceUuid, characteristicUuid, state);91 } else if (type === 'descriptorsDiscover') {92 this.emit('descriptorsDiscover', peripheralUuid, serviceUuid, characteristicUuid, descriptors);93 } else if (type === 'valueRead') {94 this.emit('valueRead', peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid, data);95 } else if (type === 'valueWrite') {96 this.emit('valueWrite', peripheralUuid, serviceUuid, characteristicUuid, descriptorUuid);97 } else if (type === 'handleRead') {98 this.emit('handleRead', peripheralUuid, handle, data);99 } else if (type === 'handleWrite') {100 this.emit('handleWrite', peripheralUuid, handle);101 } else if (type === 'handleNotify') {102 this.emit('handleNotify', peripheralUuid, handle, data);103 }104};105NobleBindings.prototype._sendCommand = function(command, errorCallback) {106 var message = JSON.stringify(command);107 this._ws.send(message, function(error) {108 if (error != null) {109 console.warn("could not send command", command, error);110 if (typeof errorCallback === "function") {111 errorCallback(error);112 }113 }114 });115};116NobleBindings.prototype.startScanning = function(serviceUuids, allowDuplicates) {117 this._startScanCommand = {118 action: 'startScanning',119 serviceUuids: serviceUuids,120 allowDuplicates: allowDuplicates121 };122 this._sendCommand(this._startScanCommand);123 this.emit('scanStart');124};125NobleBindings.prototype.stopScanning = function() {126 this._startScanCommand = null;127 this._sendCommand({128 action: 'stopScanning'129 });130 this.emit('scanStop');131};132NobleBindings.prototype.connect = function(deviceUuid) {133 var peripheral = this._peripherals[deviceUuid];134 this._sendCommand({135 action: 'connect',136 peripheralUuid: peripheral.uuid137 });138};139NobleBindings.prototype.disconnect = function(deviceUuid) {140 var peripheral = this._peripherals[deviceUuid];141 this._sendCommand({142 action: 'disconnect',143 peripheralUuid: peripheral.uuid144 });145};146NobleBindings.prototype.updateRssi = function(deviceUuid) {147 var peripheral = this._peripherals[deviceUuid];148 this._sendCommand({149 action: 'updateRssi',150 peripheralUuid: peripheral.uuid151 });152};153NobleBindings.prototype.discoverServices = function(deviceUuid, uuids) {154 var peripheral = this._peripherals[deviceUuid];155 this._sendCommand({156 action: 'discoverServices',157 peripheralUuid: peripheral.uuid,158 uuids: uuids159 });160};161NobleBindings.prototype.discoverIncludedServices = function(deviceUuid, serviceUuid, serviceUuids) {162 var peripheral = this._peripherals[deviceUuid];163 this._sendCommand({164 action: 'discoverIncludedServices',165 peripheralUuid: peripheral.uuid,166 serviceUuid: serviceUuid,167 serviceUuids: serviceUuids168 });169};170NobleBindings.prototype.discoverCharacteristics = function(deviceUuid, serviceUuid, characteristicUuids) {171 var peripheral = this._peripherals[deviceUuid];172 this._sendCommand({173 action: 'discoverCharacteristics',174 peripheralUuid: peripheral.uuid,175 serviceUuid: serviceUuid,176 characteristicUuids: characteristicUuids177 });178};179NobleBindings.prototype.read = function(deviceUuid, serviceUuid, characteristicUuid) {180 var peripheral = this._peripherals[deviceUuid];181 this._sendCommand({182 action: 'read',183 peripheralUuid: peripheral.uuid,184 serviceUuid: serviceUuid,185 characteristicUuid: characteristicUuid186 });187};188NobleBindings.prototype.write = function(deviceUuid, serviceUuid, characteristicUuid, data, withoutResponse) {189 var peripheral = this._peripherals[deviceUuid];190 this._sendCommand({191 action: 'write',192 peripheralUuid: peripheral.uuid,193 serviceUuid: serviceUuid,194 characteristicUuid: characteristicUuid,195 data: data.toString('hex'),196 withoutResponse: withoutResponse197 });198};199NobleBindings.prototype.broadcast = function(deviceUuid, serviceUuid, characteristicUuid, broadcast) {200 var peripheral = this._peripherals[deviceUuid];201 this._sendCommand({202 action: 'broadcast',203 peripheralUuid: peripheral.uuid,204 serviceUuid: serviceUuid,205 characteristicUuid: characteristicUuid,206 broadcast: broadcast207 });208};209NobleBindings.prototype.notify = function(deviceUuid, serviceUuid, characteristicUuid, notify) {210 var peripheral = this._peripherals[deviceUuid];211 this._sendCommand({212 action: 'notify',213 peripheralUuid: peripheral.uuid,214 serviceUuid: serviceUuid,215 characteristicUuid: characteristicUuid,216 notify: notify217 });218};219NobleBindings.prototype.discoverDescriptors = function(deviceUuid, serviceUuid, characteristicUuid) {220 var peripheral = this._peripherals[deviceUuid];221 this._sendCommand({222 action: 'discoverDescriptors',223 peripheralUuid: peripheral.uuid,224 serviceUuid: serviceUuid,225 characteristicUuid: characteristicUuid226 });227};228NobleBindings.prototype.readValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid) {229 var peripheral = this._peripherals[deviceUuid];230 this._sendCommand({231 action: 'readValue',232 peripheralUuid: peripheral.uuid,233 serviceUuid: serviceUuid,234 characteristicUuid: characteristicUuid,235 descriptorUuid: descriptorUuid236 });237};238NobleBindings.prototype.writeValue = function(deviceUuid, serviceUuid, characteristicUuid, descriptorUuid, data) {239 var peripheral = this._peripherals[deviceUuid];240 this._sendCommand({241 action: 'writeValue',242 peripheralUuid: peripheral.uuid,243 serviceUuid: serviceUuid,244 characteristicUuid: characteristicUuid,245 descriptorUuid: descriptorUuid,246 data: data.toString('hex')247 });248};249NobleBindings.prototype.readHandle = function(deviceUuid, handle) {250 var peripheral = this._peripherals[deviceUuid];251 this._sendCommand({252 action: 'readHandle',253 peripheralUuid: peripheral.uuid,254 handle: handle255 });256};257NobleBindings.prototype.writeHandle = function(deviceUuid, handle, data, withoutResponse) {258 var peripheral = this._peripherals[deviceUuid];259 this._sendCommand({260 action: 'writeHandle',261 peripheralUuid: peripheral.uuid,262 handle: handle,263 data: data.toString('hex'),264 withoutResponse: withoutResponse265 });266};...

Full Screen

Full Screen

Uuid.js.uncompressed.js

Source:Uuid.js.uncompressed.js Github

copy

Full Screen

1define("dojox/uuid/Uuid", ['dojo/_base/lang', './_base'], function(dojo, uuid){2dojox.uuid.Uuid = function(/*String?*/ input){3 // summary:4 // This is the constructor for the Uuid class. The Uuid class offers5 // methods for inspecting existing UUIDs.6 // input: A 36-character string that conforms to the UUID spec.7 // examples:8 // var uuid;9 // uuid = new dojox.uuid.Uuid("3b12f1df-5232-4804-897e-917bf397618a");10 // uuid = new dojox.uuid.Uuid(); // "00000000-0000-0000-0000-000000000000"11 // uuid = new dojox.uuid.Uuid(dojox.uuid.generateRandomUuid());12 // uuid = new dojox.uuid.Uuid(dojox.uuid.generateTimeBasedUuid());13 // dojox.uuid.Uuid.setGenerator(dojox.uuid.generateRandomUuid);14 // uuid = new dojox.uuid.Uuid();15 // dojox.uuid.assert(!uuid.isEqual(dojox.uuid.NIL_UUID));16 this._uuidString = dojox.uuid.NIL_UUID;17 if(input){18 dojox.uuid.assert(dojo.isString(input));19 this._uuidString = input.toLowerCase();20 dojox.uuid.assert(this.isValid());21 }else{22 var ourGenerator = dojox.uuid.Uuid.getGenerator();23 if(ourGenerator){24 this._uuidString = ourGenerator();25 dojox.uuid.assert(this.isValid());26 }27 }28};29dojox.uuid.Uuid.compare = function(/*dojox.uuid.Uuid*/ uuidOne, /*dojox.uuid.Uuid*/ uuidTwo){30 // summary:31 // Given two UUIDs to compare, this method returns 0, 1, or -1.32 // description:33 // This method is designed to be used by sorting routines, like the34 // JavaScript built-in Array sort() method. This implementation is35 // intended to match the sample implementation in IETF RFC 4122:36 // http://www.ietf.org/rfc/rfc4122.txt37 // uuidOne: Any object that has toString() method that returns a 36-character string that conforms to the UUID spec.38 // uuidTwo: Any object that has toString() method that returns a 36-character string that conforms to the UUID spec.39 // examples:40 // var uuid;41 // var generator = dojox.uuid.TimeBasedGenerator;42 // var a = new dojox.uuid.Uuid(generator);43 // var b = new dojox.uuid.Uuid(generator);44 // var c = new dojox.uuid.Uuid(generator);45 // var array = new Array(a, b, c);46 // array.sort(dojox.uuid.Uuid.compare);47 var uuidStringOne = uuidOne.toString();48 var uuidStringTwo = uuidTwo.toString();49 if (uuidStringOne > uuidStringTwo) return 1; // integer50 if (uuidStringOne < uuidStringTwo) return -1; // integer51 return 0; // integer (either 0, 1, or -1)52};53dojox.uuid.Uuid.setGenerator = function(/*Function?*/ generator){54 // summary:55 // Sets the default generator, which will be used by the56 // "new dojox.uuid.Uuid()" constructor if no parameters57 // are passed in.58 // generator: A UUID generator function, such as dojox.uuid.generateTimeBasedUuid.59 dojox.uuid.assert(!generator || dojo.isFunction(generator));60 dojox.uuid.Uuid._ourGenerator = generator;61};62dojox.uuid.Uuid.getGenerator = function(){63 // summary:64 // Returns the default generator. See setGenerator().65 return dojox.uuid.Uuid._ourGenerator; // generator (A UUID generator, such as dojox.uuid.TimeBasedGenerator).66};67dojox.uuid.Uuid.prototype.toString = function(){68 // summary:69 // This method returns a standard 36-character string representing70 // the UUID, such as "3b12f1df-5232-4804-897e-917bf397618a".71 return this._uuidString; // string72};73dojox.uuid.Uuid.prototype.compare = function(/*dojox.uuid.Uuid*/ otherUuid){74 // summary:75 // Compares this UUID to another UUID, and returns 0, 1, or -1.76 // description:77 // This implementation is intended to match the sample implementation78 // in IETF RFC 4122: http://www.ietf.org/rfc/rfc4122.txt79 // otherUuid: Any object that has toString() method that returns a 36-character string that conforms to the UUID spec.80 return dojox.uuid.Uuid.compare(this, otherUuid); // integer (either 0, 1, or -1)81};82dojox.uuid.Uuid.prototype.isEqual = function(/*dojox.uuid.Uuid*/ otherUuid){83 // summary:84 // Returns true if this UUID is equal to the otherUuid, or false otherwise.85 // otherUuid: Any object that has toString() method that returns a 36-character string that conforms to the UUID spec.86 return (this.compare(otherUuid) == 0); // boolean87};88dojox.uuid.Uuid.prototype.isValid = function(){89 // summary:90 // Returns true if the UUID was initialized with a valid value.91 return dojox.uuid.isValid(this);92};93dojox.uuid.Uuid.prototype.getVariant = function(){94 // summary:95 // Returns a variant code that indicates what type of UUID this is.96 // Returns one of the enumerated dojox.uuid.variant values.97 // example:98 // var uuid = new dojox.uuid.Uuid("3b12f1df-5232-4804-897e-917bf397618a");99 // var variant = uuid.getVariant();100 // dojox.uuid.assert(variant == dojox.uuid.variant.DCE);101 // example:102 // | "3b12f1df-5232-4804-897e-917bf397618a"103 // | ^104 // | |105 // | (variant "10__" == DCE)106 return dojox.uuid.getVariant(this);107};108dojox.uuid.Uuid.prototype.getVersion = function(){109 // summary:110 // Returns a version number that indicates what type of UUID this is.111 // Returns one of the enumerated dojox.uuid.version values.112 // example:113 // var uuid = new dojox.uuid.Uuid("b4308fb0-86cd-11da-a72b-0800200c9a66");114 // var version = uuid.getVersion();115 // dojox.uuid.assert(version == dojox.uuid.version.TIME_BASED);116 // exceptions:117 // Throws an Error if this is not a DCE Variant UUID.118 if(!this._versionNumber){119 this._versionNumber = dojox.uuid.getVersion(this);120 }121 return this._versionNumber; // dojox.uuid.version122};123dojox.uuid.Uuid.prototype.getNode = function(){124 // summary:125 // If this is a version 1 UUID (a time-based UUID), getNode() returns a126 // 12-character string with the "node" or "pseudonode" portion of the UUID,127 // which is the rightmost 12 characters.128 // exceptions:129 // Throws an Error if this is not a version 1 UUID.130 if (!this._nodeString) {131 this._nodeString = dojox.uuid.getNode(this);132 }133 return this._nodeString; // String (a 12-character string, which will look something like "917bf397618a")134};135dojox.uuid.Uuid.prototype.getTimestamp = function(/*String?*/ returnType){136 // summary:137 // If this is a version 1 UUID (a time-based UUID), this method returns138 // the timestamp value encoded in the UUID. The caller can ask for the139 // timestamp to be returned either as a JavaScript Date object or as a140 // 15-character string of hex digits.141 // returnType: Any of these five values: "string", String, "hex", "date", Date142 // returns:143 // Returns the timestamp value as a JavaScript Date object or a 15-character string of hex digits.144 // examples:145 // var uuid = new dojox.uuid.Uuid("b4308fb0-86cd-11da-a72b-0800200c9a66");146 // var date, string, hexString;147 // date = uuid.getTimestamp(); // returns a JavaScript Date148 // date = uuid.getTimestamp(Date); //149 // string = uuid.getTimestamp(String); // "Mon, 16 Jan 2006 20:21:41 GMT"150 // hexString = uuid.getTimestamp("hex"); // "1da86cdb4308fb0"151 // exceptions:152 // Throws an Error if this is not a version 1 UUID.153 if(!returnType){returnType = null};154 switch(returnType){155 case "string":156 case String:157 return this.getTimestamp(Date).toUTCString(); // String (e.g. "Mon, 16 Jan 2006 20:21:41 GMT")158 break;159 case "hex":160 // Return a 15-character string of hex digits containing the161 // timestamp for this UUID, with the high-order bits first.162 if (!this._timestampAsHexString) {163 this._timestampAsHexString = dojox.uuid.getTimestamp(this, "hex");164 }165 return this._timestampAsHexString; // String (e.g. "1da86cdb4308fb0")166 break;167 case null: // no returnType was specified, so default to Date168 case "date":169 case Date:170 // Return a JavaScript Date object.171 if (!this._timestampAsDate) {172 this._timestampAsDate = dojox.uuid.getTimestamp(this, Date);173 }174 return this._timestampAsDate; // Date175 break;176 default:177 // we got passed something other than a valid returnType178 dojox.uuid.assert(false, "The getTimestamp() method dojox.uuid.Uuid was passed a bogus returnType: " + returnType);179 break;180 }181};182return dojox.uuid.Uuid;...

Full Screen

Full Screen

uuid.py

Source:uuid.py Github

copy

Full Screen

...8# Use import to access code from other modules.9import string10import random11# Use default parameters in our function declaration to allow us to change the length and characters12def generate_uuid(length=4, characters=string.ascii_letters + string.digits):13 """Generate a string of random characters.14 Args:15 length (int, optional): The length of the UUID to generate.16 characters (string, optional): The character set used to build the UUID.17 Returns:18 string: A string representation of the generated UUID.19 """20 # Loop through a range defined by the length size21 # In each loop, make a random choice from our characters and append that to the uuid list22 uuid = []23 for _ in range(length):24 uuid.append(random.choice(characters))25 # Use join to convert the uuid list to a string26 return ''.join(uuid)27def test():28 """Run test code."""29 # Generate a uuid using default values30 uuid = generate_uuid()31 print("UUID using default values: {}".format(uuid))32 # Generate a uuid of length 16 using the default character set33 uuid16 = generate_uuid(length=16)34 print("UUID of length 16: {}".format(uuid16))35 # Generate a uuid of random numbers using the default length36 uuid_random_numbers = generate_uuid(characters=string.digits)37 print("UUID of only numbers: {}".format(uuid_random_numbers))38 # Generate a uuid consisting of only letters39 uuid_random_letters = generate_uuid(characters=string.ascii_letters)40 print("UUID of only letters: {}".format(uuid_random_letters))41 # Generate a uuid of length 8 that includes punctuation in the character set42 uuid_with_punctuation = generate_uuid(43 length=8,44 characters=string.ascii_letters + string.digits + string.punctuation)45 print("UUID with punctuation: {}".format(uuid_with_punctuation))46# This conditional will execute the test function when running as a script.47# https://docs.python.org/3/library/__main__.html48if __name__ == '__main__':...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptoolkit = require('wptoolkit');2var uuid = wptoolkit.uuid();3console.log(uuid);4var nodeuuid = require('node-uuid');5var uuid = nodeuuid.v4();6console.log(uuid);7var uuid = require('uuid');8var uuid = uuid.v4();9console.log(uuid);

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var uuid = require('node-uuid');3var page = wptools.page('Barack Obama');4page.get(function(err, resp) {5 if (err) {6 console.log(err);7 } else {8 console.log(resp);9 }10});11var page = wptools.page('Barack Obama', {uuid: uuid.v4()});12page.get(function(err, resp) {13 if (err) {14 console.log(err);15 } else {16 console.log(resp);17 }18});19var wptools = require('wptools');20var uuid = require('uuid');21var page = wptools.page('Barack Obama');22page.get(function(err, resp) {23 if (err) {24 console.log(err);25 } else {26 console.log(resp);27 }28});29var page = wptools.page('Barack Obama', {uuid: uuid.v4()});30page.get(function(err, resp) {31 if (err) {32 console.log(err);33 } else {34 console.log(resp);35 }36});37var wptools = require('wptools');38var uuid = require('node-uuid');39var page = wptools.page('Barack Obama');40page.get(function(err, resp) {41 if (err) {42 console.log(err);43 } else {44 console.log(resp);45 }46});47var page = wptools.page('Barack Obama', {uuid: uuid.v4()});48page.get(function(err, resp) {49 if (err) {50 console.log(err);51 } else {52 console.log(resp);53 }54});55var wptools = require('wptools');56var uuid = require('uuid');57var page = wptools.page('Barack Obama');58page.get(function(err, resp) {59 if (err) {60 console.log(err);61 } else {62 console.log(resp);63 }64});65var page = wptools.page('Barack Obama', {uuid: uuid.v4()});66page.get(function(err, resp) {67 if (err) {68 console.log(err);69 } else {70 console.log(resp);71 }72});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var uuid = require('node-uuid');3var page = wptools.page('Albert_Einstein');4page.get(function(err, info) {5 if (err) {6 console.log('Error: ' + err);7 } else {8 console.log(info);9 }10});11var request = require('request');12var uuid = require('node-uuid');13var wptools = function() {14 var page = function(title) {15 var self = this;16 self.get = function(callback) {17 request(url, function(error, response, body) {18 if (!error && response.statusCode == 200) {19 var data = JSON.parse(body);20 var pages = data.query.pages;21 for (var key in pages) {22 if (pages.hasOwnProperty(key)) {23 var page = pages[key];24 callback(null, page.extract);25 }26 }27 } else {28 callback(error, null);29 }30 });31 };32 };33 return {34 };35};36module.exports = wptools();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var uuid = require('uuid');3var wpt = new WebPageTest('www.webpagetest.org');4var runTest = function(url, callback) {5 var testId = uuid.v4();6 console.log('testId: ' + testId);7 wpt.runTest(url, {8 }, function(err, data) {9 if (err) return callback(err);10 console.log('Test submitted. Polling results...');11 var testUrl = data.data.userUrl;12 wpt.getTestResults(testUrl, function(err, data) {13 if (err) return callback(err);14 console.log('Got results for test %s', testUrl);15 return callback(null, data);16 });17 });18};19runTest(url, function(err, data) {20 if (err) return console.error('Error running test: %s', err);21 console.log('Got results for test %s', data.data.userUrl);22 console.log('First View Speed Index: %s', data.data.average.firstView.SpeedIndex);23 console.log('Repeat View Speed Index: %s', data.data.average.repeatView.SpeedIndex);24});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var uuid = require('uuid');3var fs = require('fs');4var data = {};5data.id = uuid.v4();6wptools.page('Albert Einstein')7 .then(function(page) {8 return page.get();9 })10 .then(function(page) {11 data.title = page.data.title;12 data.description = page.data.description;13 data.coordinates = page.data.coordinates;14 data.images = page.data.images;15 data.categories = page.data.categories;16 data.links = page.data.links;17 data.langlinks = page.data.langlinks;18 data.infobox = page.data.infobox;19 fs.writeFile('data.json', JSON.stringify(data), function(err) {20 if (err) {21 console.log(err);22 } else {23 console.log('file written');24 }25 });26 })27 .catch(function(err) {28 console.log(err);29 });30{31 "coordinates": {32 },33 {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wptools = require('wptools')2wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})3wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})4wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})5wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})6wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})7wptools.page('Eiffel Tower').getUUID().then((uuid) => {console.log(uuid)})8wptools.page('Eiffel Tower').getUUID().then((uuid)

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful