File: __init__.py

package info (click to toggle)
owfs 3.2p3+dfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster
  • size: 8,688 kB
  • sloc: ansic: 65,085; pascal: 5,957; tcl: 2,688; makefile: 1,357; python: 1,114; sh: 891; cs: 623; php: 600; perl: 587; java: 404; ruby: 289; cpp: 105; asm: 102; xml: 53
file content (458 lines) | stat: -rw-r--r-- 13,760 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""
::BOH
Copyright (c) 2006 Peter Kropf. All rights reserved.

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 2 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
::EOH

1-wire sensor network interface. ownet provides standalone access to a
owserver without the need to compile the core ow libraries on the
local system. As a result, ownet can run on almost any platform that
support Python.

OWFS is an open source project developed by Paul Alfille and hosted at
http://www.owfs.org
"""

# avoid error with python2.2
from __future__ import generators

import sys
import os
from connection import Connection

__author__ = 'Peter Kropf'
__email__ = 'pkropf@gmail.com'
__version__ = '0.3'


#
# exceptions used and thrown by the ownet classes
#

class exError(Exception):
    """base exception for all one wire raised exceptions."""


class exErrorValue(exError):
    """Base exception for all one wire raised exceptions with a value."""
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


class exNoController(exError):
    """Exception raised when a controller cannot be initialized."""


class exNotInitialized(exError):
    """Exception raised when a controller has not been initialized."""


class exUnknownSensor(exErrorValue):
    """Exception raised when a specified sensor is not found."""



#
# _server and _port are the default server and port values to be used
# if a Sensor is initialized without specifying a server and port.
#

_server      = None
_port        = None


#
# Initialize and cleanup the _server and _port default values.
#

def init(iface):
    """
    Initialize the interface mechanism to be used for communications
    to the 1-wire network. Only socket connections to owserver are
    supported.

    Examples:

        ownet.init('remote_system:3003')

    Will initialize the 1-wire interface to use the owserver running
    on remote_system on port 3003.
    """

    #print 'ownet.init(%s)' % iface
    global _server
    global _port
    pair = iface.split(':')
    if len(pair) != 2:
        raise exNoController
    _server      = pair[0]
    _port        = pair[1]


def finish():
    """
    Cleanup the OWFS library, freeing any used resources.
    """

    #print 'ownet.finish()'
    global _server
    global _port
    _server = None
    _port   = None



#
# 1-wire sensors
#

class Sensor(object):
    """
    A Sensor is the basic component of a 1-wire network. It represents
    a individual 1-wire element as it exists on the network.
    """

    def __init__(self, path, server = None, port = None, connection=None):
        """
        Create a new Sensor as it exists at the specified path.
        """
        #print 'Sensor.__init__(%s, server="%s", port=%s)' % (path, str(server), str(port))

        # setup the connection to use for connunication with the owsensor server
        if connection:
            self._connection = connection
        elif not server or not port:
            global _server
            global _port
            if not _server or not _port:
                raise exNotInitialized
            else:
                self._connection = Connection(server, port)
        else:
            self._connection = Connection(server, port)

        self._attrs = {}

        if path == '/':
            self._path    = path
            self._useCache = True
        elif path == '/uncached':
            self._path    = '/'
            self._useCache = False
        else:
            if path[:len('/uncached')] == '/uncached':
                self._path     = path[len('/uncached'):]
                self._useCache = False
            else:
                self._path     = path
                self._useCache = True

        self.useCache(self._useCache)


    def __str__(self):
        """
        Print a string representation of the Sensor in the form of:

        server:port/path - type

        Example:
        
            >>> print Sensor('/')
            xyzzy:9876/ - DS9490
        """

        #print 'Sensor.__str__'
        return "%s%s - %s" % (str(self._connection), self._usePath, self._type)


    def __repr__(self):
        """
        Print a representation of the Sensor in the form of:

        Sensor(path)

        Example:

            >>> Sensor('/')
            Sensor("/", server="xyzzy", port=9876)
        """

        #print 'Sensor.__repr__'
        return 'Sensor("%s", server="%s", port=%i)' % (self._usePath, self._connection._server, self._connection._port)


    def __eq__(self, other):
        """
        Two sensors are considered equal if their paths are
        equal. This is done by comparing their _path attributes so
        that cached and uncached Sensors compare equal.

        Examples:
        
            >>> Sensor('/') == Sensor('/1F.440701000000')
            False

            >>> Sensor('/') == Sensor('/uncached')
            True
        """

        #print 'Sensor.__eq__(%s)' % str(other)
        return self._path == other._path


    def __hash__(self):
        """
        Return a hash for the Sensor object's name. This allows
        Sensors to be used better in sets.Set.
        """

        #print 'Sensor.__hash__'
        return hash(self._path)


    def __getattr__(self, name):
        """
        Retreive an attribute from the sensor. __getattr__ is called
        only if the named item doesn't exist in the Sensor's
        namespace. If it's not in the namespace, look for the attribute
        on the physical sensor.

        Usage:

            s = ownet.Sensor('/1F.5D0B01000000')
            print s.family, s.PIO_0

        will result in the family and PIO.0 values being read from the
        sensor and printed. In this example, the family would be 1F
        and thr PIO.0 might be 1.
        """

        try:
            #print 'Sensor.__getattr__(%s)' % name
            attr = self._connection.read(object.__getattribute__(self, '_attrs')[name])
        except:
            raise AttributeError(name)

        return attr


    def __setattr__(self, name, value):
        """
        Set the value of a sensor attribute. This is accomplished by
        first determining if the physical sensor has the named
        attribute. If it does, then the value is written to the
        name. Otherwise, the Sensor's dictionary is updated with the
        name and value.

        Usage:

            s = ownet.Sensor('/1F.5D0B01000000')
            s.PIO_1 = '1'

        will set the value of PIO.1 to 1.
        """

        #print 'Sensor.__setattr__(%s, %s)' % (name, value)

        # Life can get tricky when using __setattr__. Self doesn't
        # have an _attrs atribute when it's initially created. _attrs
        # is only there after it's been set in __init__. So we can
        # only reference it if it's already been added.
        if hasattr(self, '_attrs'):
            if name in self._attrs:
                self._connection.write(self._attrs[name], value)
            else:
                self.__dict__[name] = value
        else:
            self.__dict__[name] = value


    def useCache(self, use_cache):
        """
        Set the sensor to use the underlying owfs cache (or not)
        depending on the use_cache parameter.

        Usage:

            s = ownet.Sensor('/1F.5D0B01000000')
            s.useCache(False)

        will set the internal sensor path to /uncached/1F.5D0B01000000.

        Also:

            s = ownet.Sensor('/uncached/1F.5D0B01000000')
            s.useCache(True)

        will set the internal sensor path to /1F.5D0B01000000.
        """

        #print 'Sensor.useCache(%s)' % str(use_cache)
        self._useCache = use_cache
        if self._useCache:
            self._usePath = self._path
        else:
            if self._path == '/':
                self._usePath = '/uncached'
            else:
                self._usePath = '/uncached' + self._path

        if self._path == '/':
            self._type    = self._connection.read('/system/adapter/name.0')
        else:
            self._type  = self._connection.read('%s/type' % self._usePath)

        self._attrs = dict([(n.replace('.', '_'), self._usePath + '/' + n) for n in self.entries()])


    def entries(self):
        """
        Generator which yields the attributes of a sensor.
        """
        #print 'Sensor.entries()'
        list = self._connection.dir(self._usePath)
        if self._path == '/':
            for entry in list:
                if not '/' in entry:
                    yield entry
        else:
            for entry in list:
                yield entry.split('/')[-1]


    def entryList(self):
        """
        List of the sensor's attributes.

        Example:

            >>> Sensor("/10.B7B64D000800").entryList()
            ['address', 'crc8', 'die', 'family', 'id', 'power',
            'present', 'temperature', 'temphigh', 'templow',
            'trim', 'trimblanket', 'trimvalid', 'type']
        """
        #print 'Sensor.entryList()'
        return [e for e in self.entries()]


    def sensors(self, names = ['main', 'aux']):
        """
        Generator which yields all the sensors that are associated
        with the current sensor.

        In the event that the current sensor is the adapter (such as a
        DS9490 USB adapter) the list of sensors directly attached to
        the 1-wire network will be yielded.

        In the event that the current sensor is a microlan controller
        (such as a DS2409) the list of directories found in the names
        list parameter will be searched and any sensors found will be
        yielded. The names parameter defaults to ['main', 'aux'].
        """

        #print 'Sensor.sensors(%s)' % str(names)
        if self._type == 'DS2409':
            for branch in names:
                path = self._usePath + '/' + branch
                list = filter(lambda x: '/' in x, self._connection.dir(path))
                if list:
                    namelist = ','.join(list)
                    #print 'Sensor.sensors namelist(%s)' % str(namelist)
                    for branch_entry in namelist.split(','):
                        # print 'branch_entry(%s)' % str(branch_entry)
                        try:
                            self._connection.read(branch_entry + '/type')
                        except exUnknownSensor as ex:
                            continue
                        yield Sensor(branch_entry, connection=self._connection)

        else:
            list = self._connection.dir(self._usePath)
            if self._path == '/':
                for entry in list:
                    if '/' in entry:
                        yield Sensor(entry, connection=self._connection)
                

    def sensorList(self, names = ['main', 'aux']):
        """
        List of all the sensors that are associated with the current
        sensor.

        In the event that the current sensor is the adapter (such as a
        DS9490 USB adapter) the list of sensors directly attached to
        the 1-wire network will be yielded.

        In the event that the current sensor is a microlan controller
        (such as a DS2409) the list of directories found in the names
        list parameter will be searched and any sensors found will be
        yielded. The names parameter defaults to ['main', 'aux'].

        Example:

            >>> Sensor("/1F.440701000000").sensorList()
            [Sensor("/1F.440701000000/main/29.400900000000")]
        """

        #print 'Sensor.sensorList(%s)' % str(names)
        return [s for s in self.sensors()]


    def find(self, **keywords):
        """
        Generator which yields all the sensors whose attributes match
        those past in. By default, any matched attribute will yield a
        sensor. If the parameter all is passed to the find call, then
        all the supplied attributes must match to yield a sensor.

        Usage:

            for s in Sensor('/').find(type = 'DS2408'):
                print s

        will print all the sensors whose type is DS2408.

            root = Sensor('/')
            print len([s for s in root.find(all = True,
                                               family = '1F',
                                               type = 'DS2409')])

        will print the count of sensors whose family is 1F and whose
        type is DS2409.
        """
        #print 'Sensor.find', keywords
        #recursion = keywords.pop('recursion', False)
        all       = keywords.pop('all',       False)

        for sensor in self.sensors():
            match = 0
            for attribute in keywords:
                if hasattr(sensor, attribute):
                    if keywords[attribute]:
                        if getattr(sensor, attribute) == keywords[attribute]:
                            match = match + 1
                    else:
                        if hasattr(sensor, attribute):
                            match = match + 1

            if not all and match:
                yield sensor
            elif all and match == len(keywords):
                yield sensor