Advertisement
novski

multiple_w1_things

Nov 14th, 2019
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.91 KB | None | 0 0
  1. #!/usr/bin/python
  2. # coding=utf-8
  3. from __future__ import division, print_function
  4. from webthing import (Action, Event, MultipleThings, Property, Thing, Value,
  5.                       WebThingServer)
  6. import logging
  7. import random
  8. import time
  9. import tornado.ioloop
  10. import uuid
  11. import os, sys
  12.  
  13. device_id_list = []
  14. things_list = []
  15.  
  16. class TemperatureSensors(Thing):
  17.     """A Temperature sensor which updates its measurement every few seconds."""
  18.  
  19.     def __init__(self, device, number):
  20.         Thing.__init__(
  21.             self,
  22.             'urn:dev:ops:'+str(device),
  23.             'Temperature Sensor '+str(number),
  24.             ['TemperatureSensor'],
  25.             'a web connected temperature sensor'
  26.         )
  27.         self.device = device
  28.         self.level = Value(0.0)
  29.         self.add_property(
  30.             Property(self,
  31.                      'level',
  32.                      self.level,
  33.                      metadata={
  34.                          '@type': 'TemperatureProperty',
  35.                          'title': 'Temperature',
  36.                          'type': 'number',
  37.                          'description': 'The current temperature in °C',
  38.                          'unit': 'degree celsius',
  39.                          'readOnly': True,
  40.                      }))
  41.  
  42.         logging.debug('starting the sensor update looping task for: '+str(self.device))
  43.         self.timer = tornado.ioloop.PeriodicCallback(
  44.             self.update_level,
  45.             30000
  46.         )
  47.         self.timer.start()
  48.  
  49.     def update_level(self):
  50.         new_level = read_one(self.device)
  51.         logging.debug('setting new temperature level: %s of %s', new_level, device)
  52.         self.level.notify_of_external_update(new_level)
  53.  
  54.  
  55.     def cancel_update_level_task(self):
  56.         self.timer.stop()
  57.  
  58. #********************** for multiple_ds18b20 ********************
  59. """Sensor initializeing, get the ammount of devices connected to the bus."""
  60. def get_devices():
  61.     try:
  62.         for x in os.listdir("/sys/bus/w1/devices"):
  63.             if "master" in x:
  64.                 continue
  65.             device_id_list.append(x)
  66.     except:
  67.         logging.debug('no devices found')
  68.  
  69.     logging.debug('list of devices found: %s ', device_id_list)
  70.     return device_id_list
  71. def read_one(temp_sensor_id):
  72.     try:
  73.         """ read 1-wire slave file from a specific device """
  74.         file_name = "/sys/bus/w1/devices/" + temp_sensor_id + "/w1_slave"
  75.         file = open(file_name)
  76.         filecontent = file.read()
  77.         file.close()
  78.         """ read temperature values and convert to readable float """
  79.         stringvalue = filecontent.split("\n")[1].split(" ")[9]
  80.         sensorvalue = float(stringvalue[2:]) / 1000
  81.         temperature = '%6.2f' % sensorvalue
  82.         return temperature
  83.     except:
  84.         logging.debug("not able to read from: ",temp_sensor_id)
  85.  
  86.  
  87. devices = get_devices()
  88. num = 0
  89. for device in devices:
  90.     num += 1
  91.     sensor = TemperatureSensors(device,num)
  92.     things_list.append(sensor)
  93. #********************** for multiple_ds18b20 ********************
  94.  
  95.  
  96. def run_server():
  97.     """
  98.    If adding more than one thing, use MultipleThings() with a name.
  99.    In the single thing case, the thing's name will be broadcast.
  100.    """
  101.     server = WebThingServer(MultipleThings(things_list,
  102.                                            'TemperatureDevice'),
  103.                             port=8888)
  104.     try:
  105.         logging.info('starting the server')
  106.         server.start()
  107.     except KeyboardInterrupt:
  108.         logging.debug('canceling the sensor update looping task')
  109.         for sensor in things_list:
  110.             sensor.cancel_update_level_task()
  111.         logging.info('stopping the server')
  112.         server.stop()
  113.         logging.info('done')
  114.  
  115.  
  116. if __name__ == '__main__':
  117.     logging.basicConfig(
  118.         level=10,
  119.         format="%(asctime)s %(filename)s:%(lineno)s %(levelname)s %(message)s"
  120.     )
  121.     run_server()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement