コード例 #1
0
    def __init__(self, gpio: int, urn: str, title: str, description: str):
        Thing.__init__(
            self,
            urn,
            title,
            ['OnOffSwitch', 'Light'],
            description
        )

        self.add_property(
            Property(self,
                     'on',
                     Value(False, lambda v:
                         self.toggle_level(gpio,v)
                         ),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Sprinkler state',
                     }))

        self.add_property(
            Property(self,
                     'brightness',
                     Value(120, lambda v: logging.info('Timeout is now %d min. %d sec.',  v / 60 , v % 60)),
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Durée',
                         'type': 'integer',
                         'description': 'Time of sprinkle from 60 to 300 seconds',
                         'minimum': 60,
                         'maximum': 300,
                         'unit': 'second',
                     }))
コード例 #2
0
    def __init__(self, name):
        self.name = name
        Thing.__init__(self, 'urn:dev:ops:'+name, name, ['OnOffSwitch', 'Light'], 'A virtual Unity light')
        self.add_property(
            Property(self,
                     'on',
                     Value(True, lambda v: print('On-State is now', v)),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Whether the lamp is turned on',
                     }))

        self.add_property(
            Property(self,
                     'brightness',
                     Value(50, lambda v: print('Brightness is now', v)),
                     metadata={
                         '@type': 'BrightnessProperty',
                         'title': 'Brightness',
                         'type': 'integer',
                         'description': 'The level of light from 0-100',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                     }))
コード例 #3
0
class SenseHatThing(Thing):
    """A Thing which updates its measurement every few seconds."""
    def __init__(self):
        Thing.__init__(self, 'urn:dev:ops:my-sense-hat-1234', 'My Sense Hat',
                       ['MultiLevelSensor'], 'A web connected sense hat')
        self.sense = SenseHat()
        self.sense.set_imu_config(False, True, False)
        self.compass = Value(0.0)
        self.add_property(
            Property(self,
                     'compass',
                     self.compass,
                     metadata={
                         'title': 'Compass',
                         'type': 'number',
                         'description': 'Angle to North',
                         'unit': 'º',
                         'minimum': 0,
                         'maximum': 360,
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.timer = tornado.ioloop.PeriodicCallback(self.update_properties,
                                                     1000)
        self.timer.start()

    def update_properties(self):
        compass = self.sense.get_compass()
        logging.debug("update: compass=%s", compass)
        self.compass.notify_of_external_update(compass)

    def cancel_update_properties_task(self):
        self.timer.stop()
コード例 #4
0
    def __init__(self, tet):
        Thing.__init__(self, 'Tetrahedron', ['OnOffSwitch', 'Light'],
                       'A tetrahedron shaped LED art installation.')

        self.on = False
        self.tetrahedron = tet

        self.add_property(
            Property(self,
                     'on',
                     Value(self.on, self.set_on_off),
                     metadata={
                         '@type': 'OnOffProperty',
                         'title': 'On/Off',
                         'type': 'boolean',
                         'description': 'Whether the tetrahedron is turned on',
                     }))

        self.add_property(
            Property(self,
                     'brightness',
                     Value(50),
                     metadata={
                         '@type': 'BrightnessProperty',
                         'title': 'Brightness',
                         'type': 'integer',
                         'description': 'The level of tetrahedron from 0-100',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                     }))
コード例 #5
0
    def __init__(self, deviceid):
        self.deviceid = deviceid
        Thing.__init__(self, 'myhumidsensor:{}'.format(self.deviceid),
                       'My {} Humidity Sensor'.format(self.deviceid),
                       ['MultiLevelSensor'], 'A web connected Humid sensor')

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Humidity',
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.timer = tornado.ioloop.PeriodicCallback(self.update_level, 60000)
        self.timer.start()
コード例 #6
0
    def __init__(self):
        self.update_period: int = 1500
        Thing.__init__(
            self,
            'urn:dev:ops:my-humidity-sensor-1234',
            'My Humidity Sensor',
            ['MultiLevelSensor'],
            'A web connected humidity sensor'
        )

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Humidity',
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.timer = tornado.ioloop.PeriodicCallback(
            self.update_level,
            self.update_period
        )
        self.timer.start()
コード例 #7
0
ファイル: proxy.py プロジェクト: byoungb/garage-iot
 def __init__(self):
     super(GarageDoor, self).__init__(
         id_='urn:dev:ops:garage-door',
         title='Garage Door',
         type_=['DoorSensor'],
         description='The garage door',
     )
     self.is_open = Value(False)
     self.add_property(
         Property(
             thing=self,
             name='is_open',
             value=self.is_open,
             metadata={
                 '@type': 'OpenProperty',
                 'title': 'Open/Close',
                 'type': 'boolean',
                 'description': 'Whether the garage door is open',
             },
         ),
     )
     self.add_available_action(
         name='toggle',
         metadata={
             'title': 'Open/Close',
             '@type': 'ToggleAction',
             'description': 'Open/Close Garage Door',
         },
         cls=ToggleAction,
     )
     self.timer = PeriodicCallback(
         callback=self.update_level,
         callback_time=30000,
     )
     self.timer.start()
コード例 #8
0
    def __init__(self):
        Thing.__init__(self, 'My Humidity Sensor', 'multiLevelSensor',
                       'A web connected humidity sensor')

        self.add_property(
            Property(self,
                     'on',
                     Value(True),
                     metadata={
                         'type': 'boolean',
                         'description': 'Whether the sensor is on',
                     }))

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'unit': '%',
                     }))

        logging.debug('starting the sensor update looping task')
        self.sensor_update_task = \
            get_event_loop().create_task(self.update_level())
コード例 #9
0
    def __init__(self):
        self.thing = Thing('My Humidity Sensor', 'multiLevelSensor',
                           'A web connected humidity sensor')

        self.thing.add_property(
            Property(self.thing,
                     'on',
                     Value(True),
                     metadata={
                         'type': 'boolean',
                         'description': 'Whether the sensor is on',
                     }))

        self.level = Value(0.0)
        self.thing.add_property(
            Property(self.thing,
                     'level',
                     self.level,
                     metadata={
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'unit': '%',
                     }))

        self.ioloop = tornado.ioloop.IOLoop.current()
        t = threading.Thread(target=self.update_level)
        t.daemon = True
        t.start()
コード例 #10
0
    def __init__(self, gpio_number, name, description):
        Thing.__init__(self, 'urn:dev:ops:illuminanceSensor-1',
                       'Illuminance ' + name + ' Sensor', ['MultiLevelSensor'],
                       description)

        self.bright = Value(0)
        self.add_property(
            Property(self,
                     'brightness',
                     self.bright,
                     metadata={
                         '@type': 'BrightnessProperty',
                         'title': 'Brightness',
                         "type": "integer",
                         'minimum': 0,
                         'maximum': 100,
                         'unit': 'percent',
                         'description': '"The level of light from 0-100',
                         'readOnly': True,
                     }))

        self.ioloop = tornado.ioloop.IOLoop.current()
        logging.info('bind to gpio ' + str(gpio_number))
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(gpio_number, GPIO.IN)
        GPIO.add_event_detect(gpio_number,
                              GPIO.BOTH,
                              callback=self.__update,
                              bouncetime=5)
        self.__update(gpio_number)
コード例 #11
0
 def create_wot_property(self,
                         thing_instance,
                         *,
                         name,
                         initial_value,
                         description,
                         value_source_fn=None,
                         value_forwarder=None,
                         **kwargs):
     """this method is used to add a new Thing Property to an intializing instance of a WoTThing.
     It is invoked as a partial functon"""
     if value_forwarder is None:
         value = Value(initial_value)
     else:
         logging.debug('CREATING property {} with initial value {}'.format(
             name, initial_value))
         value = Value(initial_value,
                       value_forwarder=partial(value_forwarder,
                                               thing_instance))
         logging.debug('new value {} is {}'.format(name, value.last_value))
     property_metadata = {
         "type": pytype_as_wottype(initial_value),
         "description": description,
     }
     if kwargs:
         property_metadata.update(kwargs)
     thing_instance.add_property(
         Property(thing_instance, name, value, property_metadata))
コード例 #12
0
    def __init__(self, poll_delay):
        Thing.__init__(
            self,
            "urn:dev:ops:tsl2561-lux-sensor",
            "TSL2561 Lux Sensor",
            ["MultiLevelSensor"],
            "A web connected light/lux sensor",
        )

        self.level = Value(0.0)
        self.add_property(
            Property(
                self,
                "level",
                self.level,
                metadata={
                    "@type": "LevelProperty",
                    "title": "Lux",
                    "type": "number",
                    "description": "The current light in lux",
                    "minimum": 0,
                    "maximum": 200,  # apparently 1000 is an Overcast day; typical TV studio lighting
                    "unit": "lux",
                    "readOnly": True,
                },
            )
        )

        logging.debug("starting the sensor update looping task")
        self.timer = tornado.ioloop.PeriodicCallback(self.update_level, poll_delay)
        self.timer.start()
コード例 #13
0
ファイル: 2-sensors.py プロジェクト: xtile/sensor
    def __init__(self, address):
        Thing.__init__(
            self,
            'urn:dev:ops:temperature-sensor',
            'Temperature Sensor',
            ['TemperatureSensor'],
        )

        self.sensor = DS18B20(address)

        self.temperature = Value(self.read_celsius())
        self.add_property(
            Property(self,
                     'temperature',
                     self.temperature,
                     metadata={
                         '@type': 'TemperatureProperty',
                         'title': 'Temperature',
                         'type': 'number',
                         'description': 'The current temperature in °C',
                         'minimum': -50,
                         'maximum': 70,
                         'unit': '°C',
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.timer = tornado.ioloop.PeriodicCallback(self.update, 3000)
        self.timer.start()
class OpenCvMotionSensor(Thing):
    def __init__(self):
        Thing.__init__(
            self, 'urn:dev:ops:my-maaxboard-opencv-motion-sensor',
            'OpenCV motion sensor', ['MotionSensor'],
            'On device image processing for motion detection on MaaXBoard')

        self.motion = Value(0)
        self.add_property(
            Property(self,
                     'motion',
                     self.motion,
                     metadata={
                         '@type': 'MotionProperty ',
                         'title': 'MaaxBoard Opencv Motion',
                         'type': 'boolean',
                         'description': 'Whether the motion detected',
                         'readOnly': True,
                     }))

        self.timer = tornado.ioloop.PeriodicCallback(self.update_motion, 1000)
        self.timer.start()

    def update_motion(self):
        logging.debug('motion_status %s', motion_status)
        self.motion.notify_of_external_update(motion_status)

    def cancel_update_motion_task(self):
        self.timer.stop()
コード例 #15
0
    def __init__(self, gpio_number, description):
        Thing.__init__(self, 'urn:dev:ops:eltakowsSensor-1', 'Wind Sensor',
                       ['MultiLevelSensor'], description)

        self.gpio_number = gpio_number
        self.start_time = time.time()
        self.num_raise_events = 0
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.gpio_number, GPIO.IN)
        GPIO.add_event_detect(self.gpio_number,
                              GPIO.RISING,
                              callback=self.__spin,
                              bouncetime=5)

        self.timer = tornado.ioloop.PeriodicCallback(self.__measure, 5000)

        self.windspeed = Value(0.0)
        self.add_property(
            Property(self,
                     'windspeed',
                     self.windspeed,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Windspeed',
                         'type': 'number',
                         'minimum': 0,
                         'maximum': 200,
                         'description': 'The current windspeed',
                         'unit': 'km/h',
                         'readOnly': True,
                     }))
        self.timer.start()
コード例 #16
0
 def __init__(self, id, description, data_to_measure, measures_tick):
     # Create the device
     Thing.__init__(self, 'urn:dev:ops:' + id, description,
                    ['MultiLevelSensor'], 'A web connected sensor')
     # create a variable that will be update in each measure
     self.level = Value(0.0)
     # add level property to the thing
     self.add_property(
         Property(self,
                  'level',
                  self.level,
                  metadata={
                      '@type': 'LevelProperty',
                      'title': data_to_measure,
                      'type': 'number',
                      'description':
                      'The current ' + data_to_measure + ' in %',
                      'minimum': 0,
                      'maximum': 100,
                      'unit': 'percent',
                      'readOnly': True,
                  }))
     # create a timer that will call update_level periodically
     logging.debug('starting the sensor update looping task')
     self.timer = tornado.ioloop.PeriodicCallback(self.update_level,
                                                  measures_tick)
     self.timer.start()
コード例 #17
0
ファイル: webthings.py プロジェクト: kupcimat/iot
    def __init__(self, uri_id, title, description, value_receiver):
        Thing.__init__(self, uri_id, title, ["Light"], description)

        self.add_property(
            Property(thing=self,
                     name="switch",
                     value=Value(
                         False,
                         create_value_forwarder(value_receiver, lambda x: "on" if x else "off")
                     ),
                     metadata={
                         "title": "Switch",
                         "description": "Light on/off switch",
                         "@type": "OnOffProperty",
                         "type": "boolean",
                         "readOnly": False
                     }))
        self.add_property(
            Property(thing=self,
                     name="color",
                     value=Value(
                         "#ffffff",
                         # TODO use hex value directly as arduino input?
                         create_value_forwarder(value_receiver, lambda x: int(x[1:], 16))  # convert #0000ff to 255
                     ),
                     metadata={
                         "title": "Color",
                         "description": "Light rgb color",
                         "@type": "ColorProperty",
                         "type": "string",
                         "readOnly": False
                     }))
コード例 #18
0
ファイル: webthings.py プロジェクト: kupcimat/iot
    def __init__(self, uri_id, title, description, value_receiver):
        Thing.__init__(self, uri_id, title, ["MultiLevelSwitch"], description)

        self.add_property(
            Property(thing=self,
                     name="switch",
                     value=Value(
                         False,
                         create_value_forwarder(value_receiver, lambda x: "on" if x else "off")
                     ),
                     metadata={
                         "title": "Switch",
                         "description": "Display on/off switch",
                         "@type": "OnOffProperty",
                         "type": "boolean",
                         "readOnly": False
                     }))
        self.add_property(
            Property(thing=self,
                     name="digit",
                     value=Value(
                         0,
                         create_value_forwarder(value_receiver)
                     ),
                     metadata={
                         "title": "Digit",
                         "description": "Display digit",
                         "@type": "LevelProperty",
                         "type": "integer",
                         "minimum": 0,
                         "maximum": 19,
                         "readOnly": False
                     }))
コード例 #19
0
def make_thing():
    thing = Thing('My Lamp', 'dimmableLight', 'A web connected lamp')

    def noop(_):
        pass

    thing.add_property(
        Property(thing,
                 'on',
                 Value(True, noop),
                 metadata={
                     'type': 'boolean',
                     'description': 'Whether the lamp is turned on',
                 }))
    thing.add_property(
        Property(thing,
                 'level',
                 Value(50, noop),
                 metadata={
                     'type': 'number',
                     'description': 'The level of light from 0-100',
                     'minimum': 0,
                     'maximum': 100,
                 }))

    thing.add_available_action(
        'fade', {
            'description': 'Fade the lamp to a given level',
            'input': {
                'type': 'object',
                'required': [
                    'level',
                    'duration',
                ],
                'properties': {
                    'level': {
                        'type': 'number',
                        'minimum': 0,
                        'maximum': 100,
                    },
                    'duration': {
                        'type': 'number',
                        'unit': 'milliseconds',
                    },
                },
            }
        }, FadeAction)

    thing.add_available_event(
        'overheated', {
            'description':
            'The lamp has exceeded its safe operating temperature',
            'type': 'number',
            'unit': 'celsius'
        })

    return thing
コード例 #20
0
class CPUTempSensor(Thing):
    """A CPU temperature sensor which updates its measurement every few seconds."""
    def __init__(self):
        Thing.__init__(self, 'CPU Temp ' + socket.gethostname(),
                       ['MultiLevelSensor'], 'A web connected CPU temp sensor')

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         '@type': 'LevelProperty',
                         'label': 'Temperature',
                         'type': 'number',
                         'description':
                         'The current temperature in degrees Celsius',
                         'unit': '°C',
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.sensor_update_task = \
            get_event_loop().create_task(self.update_level())

    async def update_level(self):
        try:
            while True:
                await sleep(60)
                new_level = self.get_temperature()
                logging.debug('setting new CPU temperature: %s', new_level)
                self.level.notify_of_external_update(new_level)
        except CancelledError:
            # We have no cleanup to do on cancellation so we can just halt the
            # propagation of the cancellation exception and let the method end.
            pass

    def cancel_update_level_task(self):
        self.sensor_update_task.cancel()
        get_event_loop().run_until_complete(self.sensor_update_task)

    @staticmethod
    def get_temperature():
        temps = psutil.sensors_temperatures()
        if not temps:
            sys.exit("can't read any temperature")
        for name, entries in temps.items():
            sum = 0
            count = 0
            for entry in entries:
                # print("    %-20s %s °C (high = %s °C, critical = %s °C)" % ( entry.label or name, entry.current, entry.high, entry.critical))
                sum = sum + entry.current
                count = count + 1
            average = sum / count
            #print("%s" % average)
        return average
コード例 #21
0
ファイル: 2-sensors.py プロジェクト: xtile/sensor
class HumidityTemperatureSensor(Thing):
    def __init__(self, bus, address):
        Thing.__init__(
            self,
            'urn:dev:ops:humidity-temperature-sensor',
            'Humidity+Temperature Sensor',
            ['MultiLevelSensor', 'TemperatureSensor'],
        )

        # If you want icon to show humidity:
        #   - remove type `TemperatureSensor`, and
        #   - change temperature property @type to `LevelProperty`

        self.sensor = SHT20(bus, address)

        self.humidity = Value(self.sensor.humidity().RH)
        self.add_property(
            Property(self,
                     'humidity',
                     self.humidity,
                     metadata={
                         '@type': 'LevelProperty',
                         'title': 'Humidity',
                         'unit': 'percent',
                         'readOnly': True,
                     }))

        self.temperature = Value(self.sensor.temperature().C)
        self.add_property(
            Property(self,
                     'temperature',
                     self.temperature,
                     metadata={
                         '@type': 'TemperatureProperty',
                         'title': 'Temperature',
                         'unit': '°C',
                         'readOnly': True,
                     }))

        logging.debug('starting the sensor update looping task')
        self.timer = tornado.ioloop.PeriodicCallback(self.update, 3000)
        self.timer.start()

    def update(self):
        rh, celsius = self.read_numbers()
        logging.debug('setting new humidity & temperature: %s, %s', rh,
                      celsius)
        self.humidity.notify_of_external_update(rh)
        self.temperature.notify_of_external_update(celsius)

    def cancel_update_task(self):
        self.timer.stop()

    def read_numbers(self):
        h, t = self.sensor.all()
        return h.RH, t.C
コード例 #22
0
 def __init__(self):
     Thing.__init__(self, 'urn:dev:ops:my-picam-thing-1234',
                    'My PiCamera Thing', ['VideoCamera'],
                    'A web connected Pi Camera')
     self.terminated = False
     self.picam = picamera.PiCamera(resolution='720p', framerate=30)
     self.still_img = Value(None)
     self.add_property(
         Property(self,
                  'snapshot',
                  self.still_img,
                  metadata={
                      '@type':
                      'ImageProperty',
                      'title':
                      'Snapshot',
                      'type':
                      'null',
                      'readOnly':
                      True,
                      'links': [{
                          'rel': 'alternate',
                          'href': '/media/snapshot',
                          'mediaType': 'image/jpeg'
                      }]
                  }))
     #self.stream_active = Value(False)
     #self.add_property(
     #    Property(self, 'streamActive', self.stream_active,
     #            metadata = {
     #                        'title': 'Streaming',
     #                        'type': 'boolean',
     #                        }))
     self.stream = Value(None)
     self.add_property(
         Property(self,
                  'stream',
                  self.stream,
                  metadata={
                      '@type':
                      'VideoProperty',
                      'title':
                      'Stream',
                      'type':
                      'null',
                      'readOnly':
                      True,
                      'links': [{
                          'rel': 'alternate',
                          'href': '/media/stream',
                          'mediaType': 'video/x-jpeg'
                      }]
                  }))
     syslog.syslog('Starting the camera')
     self.cam_thr = threading.Thread(target=self.start_PiCam, args=())
     self.cam_thr.start()
コード例 #23
0
def run_server():
    sht = SHT20(1, 0x40)
    h, t = sht.all()
    celsius = Value(t.C)
    humidity = Value(h.RH)

    thing = Thing('urn:dev:ops:humidity-temperature-sensor', 'SHT20_Anthony',
                  ['MultiLevelSensor'])

    thing.add_property(
        Property(thing,
                 'humidity',
                 humidity,
                 metadata={
                     '@type': 'LevelProperty',
                     'title': 'Humidity',
                     'type': 'number',
                     'unit': 'percent',
                     'readOnly': True
                 }))

    thing.add_property(
        Property(thing,
                 'temperature',
                 celsius,
                 metadata={
                     '@type': 'LevelProperty',
                     'title': 'Temperature',
                     'type': 'number',
                     'unit': '°C',
                     'readOnly': True
                 }))

    server = WebThingServer(SingleThing(thing), port=8889)

    def update():
        h, t = sht.all()
        celsius.notify_of_external_update(t.C)
        humidity.notify_of_external_update(h.RH)

    timer = tornado.ioloop.PeriodicCallback(update, 3000)
    timer.start()

    try:
        logging.info('starting the server')
        server.start()
    except KeyboardInterrupt:
        logging.debug('stopping update task')
        timer.stop()
        logging.info('stopping the server')
        server.stop()
        logging.info('done')
コード例 #24
0
ファイル: decoy.py プロジェクト: SomeWan72/Cybercanary
def initialize_thing():
    thing = Thing('urn:dev:ops:smart_lamp_7256', 'SLamp',
                  ['OnOffSwitch', 'Light'],
                  'A smart lamp connected to the web')

    thing.add_property(
        Property(thing,
                 'on',
                 Value(True),
                 metadata={
                     '@type': 'SwitchProperty',
                     'title': 'On/Off',
                     'type': 'boolean',
                     'description': 'Shows if the lamp is on',
                 }))

    thing.add_property(
        Property(thing,
                 'brightness',
                 Value(50),
                 metadata={
                     '@type': 'BrightnessProperty',
                     'title': 'Brightness',
                     'type': 'integer',
                     'description': 'The light level from 0 to 100',
                     'minimum': 0,
                     'maximum': 100,
                     'unit': 'percent',
                 }))

    thing.add_available_action(
        'change_brightness', {
            'title': 'Change Brightness',
            'description': "Change the lamp brightness to a given level",
            'input': {
                'type': 'object',
                'required': [
                    'brightness',
                ],
                'properties': {
                    'brightness': {
                        'type': 'integer',
                        'minimum': 0,
                        'maximum': 100,
                        'unit': 'percent',
                    },
                },
            },
        }, ChangeBrightnessAction)

    return thing
コード例 #25
0
class FakeGpioHumiditySensor(Thing):
    """A humidity sensor which updates its measurement every few seconds."""
    def __init__(self):
        Thing.__init__(self, 'My Humidity Sensor', 'multiLevelSensor',
                       'A web connected humidity sensor')

        self.add_property(
            Property(self,
                     'on',
                     Value(True),
                     metadata={
                         'type': 'boolean',
                         'description': 'Whether the sensor is on',
                     }))

        self.level = Value(0.0)
        self.add_property(
            Property(self,
                     'level',
                     self.level,
                     metadata={
                         'type': 'number',
                         'description': 'The current humidity in %',
                         'unit': '%',
                     }))

        logging.debug('starting the sensor update looping task')
        self.sensor_update_task = \
            get_event_loop().create_task(self.update_level())

    async def update_level(self):
        try:
            while True:
                await sleep(3)
                new_level = self.read_from_gpio()
                logging.debug('setting new humidity level: %s', new_level)
                self.level.notify_of_external_update(new_level)
        except CancelledError:
            # We have no cleanup to do on cancellation so we can just halt the
            # propagation of the cancellation exception and let the method end.
            pass

    def cancel_update_level_task(self):
        self.sensor_update_task.cancel()
        get_event_loop().run_until_complete(self.sensor_update_task)

    @staticmethod
    def read_from_gpio():
        """Mimic an actual sensor updating its reading every couple seconds."""
        return 70.0 * random.random() * (-0.5 + random.random())
コード例 #26
0
ファイル: sensornode.py プロジェクト: aimas-upb/CONSERT-CaaS
def make_hue_light(client):
    thing_type = ['OnOffSwitch', 'Light',  'Philips HUE']

    thing = ThingWrapper('hue_lamp', thing_type, client, AlwaysTrue, 'Philips HUE as web thing')

    #TODO add 'availablie property'
    thing.add_property(
        Property(thing,
                 'on',
                 Value(False),
                 metadata={
                     '@type': 'OnOffProperty',
                     'title': 'On/Off',
                     'type': 'boolean',
                     'description': 'Whether the lamp is turned on',
                 }))
    thing.add_property(
        Property(thing,
                 'color',
                 Value(None),
                 metadata={
                     '@type': 'ColorProperty',
                     'title': 'Color',
                     'type': 'string',
                     'description': 'Lamp color',
                 }))

    thing.add_available_action('color',
                               {
                                   'title': 'Change color',
                                   'description': 'Change color',
                                   'metadata': {}  # TODO add metadata: input description for 'validate'
                               },
                               ChangeColor)

    thing.add_available_action('on',
                               {
                                   'title': 'Turn on',
                                   'description': 'Turn the lamp on or off',
                                   'metadata':{} #TODO add metadata: input description for 'validate'
                               },
                               OnAction)
    thing.add_available_action('off',
                               {
                                   'title': 'turn off',
                                   'description': 'Turn the lamp on or off',
                                   'metadata': {}  # TODO add metadata: input description for 'validate'
                               },
                               OffAction)
    return thing
コード例 #27
0
class LuxSensor(Thing):
    """A lux sensor which updates its measurement every few seconds."""

    def __init__(self, poll_delay):
        Thing.__init__(
            self,
            "urn:dev:ops:tsl2561-lux-sensor",
            "TSL2561 Lux Sensor",
            ["MultiLevelSensor"],
            "A web connected light/lux sensor",
        )

        self.level = Value(0.0)
        self.add_property(
            Property(
                self,
                "level",
                self.level,
                metadata={
                    "@type": "LevelProperty",
                    "title": "Lux",
                    "type": "number",
                    "description": "The current light in lux",
                    "minimum": 0,
                    "maximum": 200,  # apparently 1000 is an Overcast day; typical TV studio lighting
                    "unit": "lux",
                    "readOnly": True,
                },
            )
        )

        logging.debug("starting the sensor update looping task")
        self.timer = tornado.ioloop.PeriodicCallback(self.update_level, poll_delay)
        self.timer.start()

    def update_level(self):
        try:
            new_level = self.read_from_i2c()
            logging.debug("setting new humidity level: %s", new_level)
            self.level.notify_of_external_update(new_level)
        except socket.error:  # TODO update to appropriate IO error
            logging.error("failed to read a lux value from sensor")

    def cancel_update_level_task(self):
        self.timer.stop()

    @staticmethod
    def read_from_i2c():
        """Mimic an actual sensor updating its reading every couple seconds."""
        return sensor.lux or 0
コード例 #28
0
    def __init__(self, photos_path, static_path):
        """Initialize the thing."""
        Thing.__init__(self, 'urn:dev:ops:photo-cycler', 'Photo Cycler', [],
                       'Photo Cycler')

        self.photos_path = photos_path
        self.static_path = static_path
        self.update_rate = 5

        self.add_property(
            Property(self,
                     'updateRate',
                     Value(self.update_rate, self.set_update_rate),
                     metadata={
                         'type': 'integer',
                         'description': 'Photo cycle rate',
                         'minimum': 0,
                         'unit': 'second',
                         'title': 'Update Rate',
                     }))

        self.add_property(
            Property(self,
                     'image',
                     Value(None),
                     metadata={
                         '@type':
                         'ImageProperty',
                         'type':
                         'null',
                         'description':
                         'Current image',
                         'title':
                         'Image',
                         'readOnly':
                         True,
                         'links': [
                             {
                                 'rel': 'alternate',
                                 'href': '/static/current.jpg',
                                 'mediaType': 'image/jpeg',
                             },
                         ],
                     }))

        self.set_ui_href('/static/index.html')

        self.timer = None
        self.set_update_rate(self.update_rate)
コード例 #29
0
 def __init__(self, _location, _w1_device_id_list):
     self.location = _location
     self.id = f'urn:dev:ops:{self.location}-vorraum-node'
     self.name = f'{self.location}-node_functions'
     self.w1_device_id_list = _w1_device_id_list
     Thing.__init__(self, self.id, self.name, ['EnergyMonitor'],
                    'A web connected node')
     self.ina219 = ina219.INA219(busnum=0, address=0x40)
     self.power = Value(0.0)
     self.add_property(
         Property(self,
                  f'{self.name}-power',
                  self.power,
                  metadata={
                      '@type': 'InstantaneousPowerProperty',
                      'title': f'{self.name}-Power',
                      'type': 'float',
                      'multipleOf': 0.01,
                      'description': 'the power used by this node',
                  }))
     self.volt = Value(0.0)
     self.add_property(
         Property(self,
                  f'{self.name}-voltage',
                  self.volt,
                  metadata={
                      '@type': 'VoltageProperty',
                      'title': f'{self.name}-Voltage',
                      'type': 'float',
                      'multipleOf': 0.01,
                      'description': 'the voltage used by this node',
                  }))
     self.current = Value(0.0)
     self.add_property(
         Property(self,
                  f'{self.name}-current',
                  self.current,
                  metadata={
                      '@type': 'CurrentProperty',
                      'title': f'{self.name}-Current',
                      'type': 'float',
                      'multipleOf': 0.01,
                      'description': 'the current used by this node',
                  }))
     self.temperature = Value(0.0)
     self.add_property(
         Property(self,
                  f'{self.name}-Temperature',
                  self.temperature,
                  metadata={
                      '@type': 'TemperatureProperty',
                      'title': f'{self.name}-Temperature',
                      'type': 'float',
                      'multipleOf': 0.01,
                      'description': 'the temperature in the case',
                  }))
     self.timer = tornado.ioloop.PeriodicCallback(self.get_sensors, 300000)
     self.timer.start()
コード例 #30
0
    def __init__(self) :
        super().__init__(name = 'virtual_temperature_thing',
                         type_ = ['Temperature', 'Virtual'],
                         description = '',
                         )

        self.add_property(Property(thing = self,
                                   name = 'temperature',
                                   value = Value(20),
                                   metadata = {
                                       'label'    : 'Temperature',
                                       'type'     : 'number',
                                       "readOnly" : True,
                                       }
                                   )
                          )

        self.add_property(Property(thing = self,
                                   name = 'led',
                                   value = Value(0),
                                   metadata = {
                                       'label' : 'LED',
                                       'type'  : 'number',
                                       },
                                   )
                          )

        self.add_available_action(
                name = 'set_led_to',
                metadata = {
                    'input' : {
                        'properties' : {
                            'led' : {
                                'type' : 'number',
                                },
                            },
                        },
                    },
                cls = PostLed
                )

        self.add_available_event(
                'overheated',
                {
                    'description' : 'The lamp has exceeded its safe operating temperature',
                    'type'        : 'number',
                    'unit'        : 'celsius',
                    })