def set_mode(self, client, userdata, message):
        mode = message.payload.decode('utf-8')
        previous_mode = self.mode

        # reset PID if switching between modes
        if previous_mode != mode:
            pid_options = self.config.getPIDOptions(mode)
            temp_options = self.config.getTempOptions(mode)
            self.temp = Temp(**{**temp_options, **pid_options})

        if mode == 'off':
            self.manual = True
            self.mode = 'auto'
            self.power.state = False
            self.logger.info('Set mode to off')
        if mode == 'auto':
            self.manual = True
            self.power.state = True
            self.mode = 'auto'
            self.temp.temp_set = self.temp.temp_request
            self.logger.info('Set mode to manual')
        elif mode == 'heat':
            self.manual = False
            self.mode = mode
            self.logger.info('Set mode to %s', self.mode)
        elif mode == 'cool':
            self.manual = False
            self.mode = mode
            self.temp.temp_set = self.temp.temp_absolute
            self.logger.info('Set mode to %s', self.mode)

        self.state.setMode(mode)
        self.publish_mode()
        self.setHVAC()
        self.set_next_iteration(2)
    def __init__(self):
        self.logger = logging.getLogger('hvac-pid')
        self.logger.info('Starting hvac-pid')

        self.config = Config()
        self.util = Util()

        # PID options
        pid_options = self.config.getPIDOptions(self.mode)
        temp_options = self.config.getTempOptions(self.mode)

        # Temp
        self.temp = Temp(**{**temp_options, **pid_options})

        # Fan
        self.fan = Fan()

        # Power
        self.power = Power()

        # Occupancy state
        self.state = State(**self.config.getStateOptions())

        # MQTT
        self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX')
        self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'),
                               os.getenv('MQTT_BROKER_HOST'))
        self.mqtt.connect()

        # subscribe
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0,
                            self.temp_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0,
                            self.temp_outdoors_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0,
                            self.hvac_callback)
        self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode)
        self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0,
                            self.set_temp)
        self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0,
                            self.set_occupancy_state)

        self.logger.info('MQTT connected')

        self.publish_temp()
        self.publish_mode()
        self.publish_fan()

        self.next_iteration = datetime.now() + timedelta(minutes=2)

        # wait a bit before enabling control
        time.sleep(5)
        self.control_enable = True
Exemple #3
0
def test_lowerLimit():
    temp = Temp(**{
        'Kp': 1, 
        'Ki': 1, 
        'Kd': 1,
        'temp_min': 17,
        'temp_max': 30,
        'mode': 'heat',
    })
    temp.temp_set = 17
    temp.setMeasurement(17, 17)
    temp.setRequest(17)
    temp.iteratePID()

    assert temp.temp_set == 17
Exemple #4
0
def test_upperLimit():
    temp = Temp(**{
        'Kp': 1, 
        'Ki': 1, 
        'Kd': 1,
        'temp_min': 17,
        'temp_max': 30,
        'mode': 'heat',
    })
    temp.temp_set = 40
    temp.setMeasurement(40, 40)
    temp.setRequest(40)
    temp.iteratePID()

    assert temp.temp_set == 30
Exemple #5
0
 def __init__(self, conf, name):
     threading.Thread.__init__(self)
     self.daemon = True
     if conf["enabled"] == "true":
         self.enabled = True
     else:
         self.enabled = False
     self.gpio_number = conf["gpio_number"]
     self.target = int(conf["target"])
     self.sensor = Temp(fileName = conf["temp_sensor"], correctionFactor = conf["temp_offset"])
     self.band = conf["band"]
     self.jee = Adafruit_MCP230XX(address=0x26, num_gpios=8, busnum=1)
     self.jee.config(self.gpio_number,self.jee.OUTPUT)
     self.name = name
     self.state = conf["state"]
     self.usePid = conf["usePid"]
     self.pid_Kp = conf["pid_Kc"]
     self.pid_Ki = conf["pid_Ti"]
     self.pid_Kd = conf["pid_Td"]
     self.cycle_time = conf["cycle_time"]
     self.pid = mypid.mypid(kp=self.pid_Kp,ki=self.pid_Ki,kd=self.pid_Kd, history_depth=3)
Exemple #6
0
  def __init__(self):

    self.motionDetected = False;
    self.relay = Relays(7);
    self.relay.setAllOff();
    self.motion = Motion(0, 3, self);
    self.light = Light(3, 1000, self);
    self.temp = Temp(1, 85, self);

    self.start = time.time();

    while True:
      print('********** Switch Module Starting **********');
      time.sleep(5);
class HVACPIDController(object):
    logger = None
    mqtt = None
    temp = None
    fan = None
    power = None
    config = None
    state = None

    temp_outdoors = 0

    mode = 'auto'
    manual = False
    control_enable = False
    hvac_state = {}
    next_iteration = None

    def __init__(self):
        self.logger = logging.getLogger('hvac-pid')
        self.logger.info('Starting hvac-pid')

        self.config = Config()
        self.util = Util()

        # PID options
        pid_options = self.config.getPIDOptions(self.mode)
        temp_options = self.config.getTempOptions(self.mode)

        # Temp
        self.temp = Temp(**{**temp_options, **pid_options})

        # Fan
        self.fan = Fan()

        # Power
        self.power = Power()

        # Occupancy state
        self.state = State(**self.config.getStateOptions())

        # MQTT
        self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX')
        self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'),
                               os.getenv('MQTT_BROKER_HOST'))
        self.mqtt.connect()

        # subscribe
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0,
                            self.temp_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0,
                            self.temp_outdoors_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0,
                            self.hvac_callback)
        self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode)
        self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0,
                            self.set_temp)
        self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0,
                            self.set_occupancy_state)

        self.logger.info('MQTT connected')

        self.publish_temp()
        self.publish_mode()
        self.publish_fan()

        self.next_iteration = datetime.now() + timedelta(minutes=2)

        # wait a bit before enabling control
        time.sleep(5)
        self.control_enable = True

    def iterate(self):
        if self.manual:
            self.logger.info('Manual mode, skipping PID iteration')
        else:
            compensated_request_temp = self.state.compensateRequestTemp(
                self.temp.temp_request, self.temp_outdoors)
            max_set_temp = ceil(self.temp.temp_absolute) + 3

            # temp hax
            # limit min temp when outdoors is < -10
            if self.temp_outdoors < -10:
                self.temp.setLimits(
                    floor(compensated_request_temp) - 1, max_set_temp)
                self.logger.debug(
                    'Limiting min temp to %g when outdoor temp is %g',
                    self.temp.temp_min, self.temp_outdoors)
            else:
                self.temp.setLimits(self.config.getSetTempMin(), max_set_temp)

            self.temp.iteratePID(compensated_request_temp)
            self.fan.calculate(self.temp.pid_offset, self.mode)
            self.power.calculate(self.temp.temp_request,
                                 self.temp.temp_measure, self.mode,
                                 self.temp_outdoors)
            if not self.power.state:
                self.temp.reset()
            self.publish_state()

    def temp_update_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))

        if 'temperature' in payload_json:
            temp = payload_json['temperature']
        else:
            temp = payload_json['tempc']

        if 'humidity' in payload_json:
            humidity = payload_json['humidity']
        else:
            humidity = payload_json['hum']

        if self.mode == 'cool':
            dew_point = self.util.dewPoint(temp, humidity)
            self.temp.setMeasurement(round(dew_point, 2), temp)
        else:
            self.temp.setMeasurement(temp, temp)

    def temp_outdoors_update_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))
        self.temp_outdoors = float(payload_json['temperature'])

    def hvac_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))
        self.logger.info('Received hvac state change %s', payload_json)
        self.hvac_state = payload_json

    def setHVAC(self):
        if self.control_enable:
            topic = os.getenv('MQTT_HVAC_TOPIC')
            new_state = {
                'power': self.power.state,
                'mode': self.mode.upper(),
                'temperature': self.temp.temp_set,
                'fan': self.fan.speed,
            }

            is_state_changed = (new_state['power']
                                and self.hvac_state != new_state)
            is_power_state_changed = (
                self.hvac_state
                and new_state['power'] != self.hvac_state['power'])
            old_state_doesnt_exists = (not self.hvac_state)

            if is_state_changed or is_power_state_changed or old_state_doesnt_exists:
                message = json.dumps(new_state)

                self.logger.debug('Controlling HVAC with command %s', message)
                self.mqtt.publish(topic, message, 1)
            else:
                self.logger.debug('HVAC state unchanged %s', self.hvac_state)
        else:
            self.logger.debug('Controlling HVAC disabled')

    def set_mode(self, client, userdata, message):
        mode = message.payload.decode('utf-8')
        previous_mode = self.mode

        # reset PID if switching between modes
        if previous_mode != mode:
            pid_options = self.config.getPIDOptions(mode)
            temp_options = self.config.getTempOptions(mode)
            self.temp = Temp(**{**temp_options, **pid_options})

        if mode == 'off':
            self.manual = True
            self.mode = 'auto'
            self.power.state = False
            self.logger.info('Set mode to off')
        if mode == 'auto':
            self.manual = True
            self.power.state = True
            self.mode = 'auto'
            self.temp.temp_set = self.temp.temp_request
            self.logger.info('Set mode to manual')
        elif mode == 'heat':
            self.manual = False
            self.mode = mode
            self.logger.info('Set mode to %s', self.mode)
        elif mode == 'cool':
            self.manual = False
            self.mode = mode
            self.temp.temp_set = self.temp.temp_absolute
            self.logger.info('Set mode to %s', self.mode)

        self.state.setMode(mode)
        self.publish_mode()
        self.setHVAC()
        self.set_next_iteration(2)

    def publish_mode(self):
        if not self.control_enable:
            return

        topic = self.topic_prefix + '/mode/state'

        if self.manual:
            if self.power.state == False:
                mode = 'off'
            else:
                mode = 'manual'
        elif self.mode == 'auto':
            mode = 'manual'
        else:
            mode = self.mode

        self.mqtt.publish(topic, mode, 1, True)

    def set_temp(self, client, userdata, message):
        temp = round(float(message.payload.decode('utf-8')), 2)

        if temp >= float(os.getenv('REQUEST_MIN_TEMP', 0)) and temp <= float(
                os.getenv('REQUEST_MAX_TEMP', 100)):
            self.temp.setRequest(temp)

            if self.manual:
                self.temp.temp_set = self.temp.temp_request
            else:
                self.temp.reset()

            self.publish_temp()
            self.setHVAC()

    def publish_temp(self):
        if not self.control_enable:
            return

        self.mqtt.publish(self.topic_prefix + '/temperature/state',
                          self.temp.temp_request, 1, True)
        self.mqtt.publish(self.topic_prefix + '/measured_temperature',
                          self.temp.temp_measure, 1, True)

    def set_fan(self, client, userdata, message):
        fan = message.payload.decode('utf-8')

        if fan != "auto":
            fan_int = int(fan)

            if self.manual and fan_int >= 0 and fan_int <= 5:
                self.fan.speed = fan_int
                self.publish_fan()
                self.setHVAC()
                self.logger.info('Manually set fan speed to %s/5',
                                 self.fan.speed)

    def publish_fan(self):
        if not self.control_enable:
            return

        topic = self.topic_prefix + '/fan/state'

        if self.manual:
            fan = self.fan.speed
        else:
            fan = 'auto'

        self.mqtt.publish(topic, fan, 1, True)

    def publish_state(self):
        if not self.control_enable:
            return

        topic = os.getenv('MQTT_PID_TOPIC_PREFIX') + '/state'
        message = json.dumps({
            'mode':
            self.mode,
            'manual':
            self.manual,
            'temperature_request':
            float(self.temp.temp_request),
            'temperature_set':
            float(self.temp.temp_set),
            'temperature_measure':
            float(self.temp.temp_measure),
            'temperature_error':
            float(self.temp.pid.previous_error),
            'set_temperature_lower_limit':
            float(self.temp.temp_min),
            'set_temperature_upper_limit':
            float(self.temp.temp_max),
            'fan':
            int(self.fan.speed if self.power.state else 0),
            'power':
            self.power.state,
            'Kp':
            float(self.temp.pid.Kp),
            'Ki':
            float(self.temp.pid.Ki),
            'Kd':
            float(self.temp.pid.Kd),
            'integral':
            float(self.temp.pid.integral),
            'integral_max':
            float(self.temp.pid.integral_max),
            'pid_offset':
            float(self.temp.pid_offset),
            'pid_result':
            float(self.temp.pid_result),
        })
        self.mqtt.publish(topic, message, 1)

    def set_occupancy_state(self, client, userdata, message):
        state = message.payload.decode('utf-8')
        prev_state = self.state.state
        self.state.setState(state)
        self.logger.info('Setting occupancy state to %s', self.state.state)

        # only reset if going or returning away state
        if prev_state == 'away' or self.state.state == 'away':
            self.temp.reset()
            self.set_next_iteration(2)

    def set_next_iteration(self, interval):
        self.next_iteration = datetime.now() + timedelta(minutes=interval)
        self.logger.info('Next iteration at %s', self.next_iteration)
Exemple #8
0
    web_server.stop()
    if 'yes' == MASTER:
        my_screen.stop()
    time.sleep(0.5)
    sys.exit(0)


# The main program, start thread, then update continuously
if __name__ == '__main__':

    # Install the signal handler
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    # Create a new temp object with specified temp modifier, and polling rate
    temp = Temp(-3, 1)
    temp.start()

    # Create a new web server and bind it to the specified address:port
    web_server = MyServer(WEB_BIND_ADDRESS, WEB_BIND_PORT)
    web_server.start()

    # If this is the MASTER, setup slave URL, screen thread and web server thread
    if 'yes' == MASTER:

        # Construct the URL for getting the slave's temperature
        SLAVE_TEMP_URL = 'http://' + SLAVE_IP + ':' + str(
            WEB_BIND_PORT) + '/api/temp-F'
        debug("--> SLAVE_TEMP_URL = \"" + SLAVE_TEMP_URL + "\"")

        # Create a new screen handler object
Exemple #9
0
#battery.volts()
#print("Battery volts: {0:.2f}v".format(battery.volts()))
#if battery.alarm():
#    print('Battery Needs a charge')
#else:
#    print('Battery okay')

# roughly works ...
vin = Vin('P16', 'P10')
led = Led('P11')
battery = Battery(py)

# still need work
stateMachine = StateMachine()
bilgeSwitch = BilgeSwitch('P13')
temp = Temp('P9')
button = Button('P14')

check = Checks(led, vin, bilgeSwitch, battery, temp, stateMachine)
check.whichToDo()

# https://forum.pycom.io/topic/1626/pytrack-gps-api/12

# to sleep with GPS VBACKUP on
# should go down to 17ua
# https://forum.pycom.io/topic/2525/power-consumption/16
#
# py.go_to_sleep(True)

# tell us why we woke
# display the reset reason code and the sleep remaining in seconds
Exemple #10
0
class Kettle(threading.Thread):
    """
    A class for managing a brew kettle
    """

    def __init__(self, conf, name):
        threading.Thread.__init__(self)
        self.daemon = True
        if conf["enabled"] == "true":
            self.enabled = True
        else:
            self.enabled = False
        self.gpio_number = conf["gpio_number"]
        self.target = int(conf["target"])
        self.sensor = Temp(fileName = conf["temp_sensor"], correctionFactor = conf["temp_offset"])
        self.band = conf["band"]
        self.jee = Adafruit_MCP230XX(address=0x26, num_gpios=8, busnum=1)
        self.jee.config(self.gpio_number,self.jee.OUTPUT)
        self.name = name
        self.state = conf["state"]
        self.usePid = conf["usePid"]
        self.pid_Kp = conf["pid_Kc"]
        self.pid_Ki = conf["pid_Ti"]
        self.pid_Kd = conf["pid_Td"]
        self.cycle_time = conf["cycle_time"]
        self.pid = mypid.mypid(kp=self.pid_Kp,ki=self.pid_Ki,kd=self.pid_Kd, history_depth=3)
    def run(self):
        self.sensor.start()
        duty = 0
        while True:
            if self.state == "control":
                self.sensor.setEnabled(True)
                currentTemp = self.sensor.getCurrentTemp()
                if currentTemp != -999:
                    duty = self.getDuty(currentTemp)
                    self._updatedb(currentTemp,duty)
                #print self.name + " is targetting " + str(self.target) + " and is at " + str(currentTemp) + " and " + str(duty) 
                self._switch(duty)
            elif self.state == "monitor":
                self.sensor.setEnabled(True)
                currentTemp = self.sensor.getCurrentTemp()
                if currentTemp != 999:
                    self._updatedb(currentTemp, duty)
                    time.sleep(2)
                #print self.name + " is at " + str(currentTemp)
            else:
                self.sensor.setEnabled(False)
                self.jee.output(self.gpio_number,0)
    def getDuty(self, currentTemp):
        duty = 0
        #return manual duty
        if self.target > 299:
            return self.target - 300
        #if no temp is given, turn it off.
        if currentTemp == -999:
            return 0
        #insert pid logics here
        if self.usePid:
            duty = self.pid.get_duty(currentTemp, self.target)
            return duty
        #simple on/off logic
        else:
            if currentTemp < (self.target - 10):
                duty = 100
            elif (self.target - 5) < currentTemp < (self.target + self.band):
                duty = 50
            elif (self.target - 10) < currentTemp < (self.target - self.band):
                duty = 75
            else:
                duty = 0
            return duty



    def getTarget(self):
        return self.target

    def setTarget(self, target):
        self.target = int(target)

    def setEnabled(self, enabled):
        if enabled == "true":
            self.enabled = True
        else:
            self.enabled = False

    def isEnabled(self):
        return self.enabled

    def setState(self, state):
        if (state == "disabled") or (state == "monitor") or (state == "control"):
            self.state = state
        else:
            print "invalid state configured, setting state to disabled"
            self.state = "disabled"
    def getState(self):
        return self.state
    def setConfig(self, conf):
        if conf["enabled"] == "true":
            self.enabled = True
        else:
            self.enabled = False
        self.target = int(conf["target"])
        self.band = conf["band"]
        self.state = conf["state"]
        self.usePid = conf["usePid"]
        self.pid_Kp = conf["pid_Kc"]
        self.pid_Ki = conf["pid_Ti"]
        self.pid_Kd = conf["pid_Td"]
        self.cycle_time = conf["cycle_time"]

        self.pid = mypid.mypid(kp=self.pid_Kp,ki=self.pid_Ki,kd=self.pid_Kd, history_depth=3)
        '''
    Takes the pin on a jeelabs output plug and sets it to 1 or 0 depending on if the heat should be on or not.
    '''
    def _switch(self, duty_cycle):
        self.jee.config(self.gpio_number,self.jee.OUTPUT)
        cycle_time = self.cycle_time
        if duty_cycle == 100:
            self.jee.output(self.gpio_number,1)
            time.sleep(cycle_time)
        elif duty_cycle == 0:
            self.jee.output(self.gpio_number,0)
            time.sleep(cycle_time)
        else:
            duty = duty_cycle/100.0
            self.jee.output(self.gpio_number,1)
            time.sleep(cycle_time*(duty))
            self.jee.output(self.gpio_number,0)
            time.sleep(cycle_time*(1.0-duty))
        return

    '''
    takes the temperature and updates the database as well as the ramdisk file
    '''
    def _updatedb(self, temp, duty):
        try:
            logfile = "/mnt/ramdisk/" + self.name
            with open (logfile, 'w+') as f: f.write(str(temp))
        except:
            print "Error writing to ramdisk file"
        #send to graphite
        if self.state == "control":
            target=self.target
        else:
            target=0
        summary = {'temperature':temp, 'target':target, 'duty':duty}
        
        try:
            graph = graphitesend.init(graphite_server='192.168.1.3',prefix="brewing", system_name=self.name)
            graph.send_dict(summary) 
        except:
            print("error sending to graphite")
            traceback.print_exc() 
Exemple #11
0
def main():
	global temp
	if sys.argv[1] is None:
		raise ValueError('Need to set target temparature as float')
	temp = Temp(float(sys.argv[1]))
	run(server='paste', host='0.0.0.0', port=8080, debug=True, reloader=False)
Exemple #12
0
#!/usr/bin/env python
import time
import eeml
from temp import Temp

# COSM variables. API_KEY and FEED are specific
API_KEY = 'SCf8E2SZG3W68pbyUuf1qzg9umMWy6VCkHoeVuuDPEjI2SPN'
FEED = '2053937525'
API_URL = '/v2/feeds/{feednum}.xml'.format(feednum=FEED)

#replace 28-00000449ef31 below with the id of your temperature probe
sensor1 = Temp(fileName='28-000004d93f9d')
sensor2 = Temp(fileName='28-000004d9ad58')
sensor1.start()
sensor2.start()

#the rest of your code is below.
# The Temp class will be updating on its own thread which will allow you to do
#  anything you want on the main thread.
while True:

    temp1 = sensor1.getCurrentTemp()
    temp2 = sensor2.getCurrentTemp()

    print temp1
    print temp2

    #open cosm feed
    pac = eeml.Pachube(API_URL, API_KEY)

    #send fahrenheit data
Exemple #13
0
 def __init__(self, vrtx, edge, attr, router=None, core=None, rdonly=True):
     Entry.__init__(self, router, core)
     self._temp = Temp(self, rdonly)
     self._vrtx = vrtx
     self._edge = edge
     self._attr = attr
Exemple #14
0
class Data(Entry):
    def __init__(self, vrtx, edge, attr, router=None, core=None, rdonly=True):
        Entry.__init__(self, router, core)
        self._temp = Temp(self, rdonly)
        self._vrtx = vrtx
        self._edge = edge
        self._attr = attr

    def can_load(self):
        return True

    def can_scan(self):
        return True

    def can_enable(self):
        return True

    def can_disable(self):
        return True

    def truncate(self, uid, name, length):
        path = self.get_path(uid, name)
        self._fs.truncate(uid, path, length)
        self._temp.truncate(uid, name, length)

    def getattr(self, uid, name):
        return self.lsattr(uid, name)

    def create(self, uid, name):
        self.check_path(uid, name)
        self._vrtx.check_path(uid, parent=name)
        self._edge.check_path(uid, parent=name)
        self._attr.check_path(uid, parent=name)
        return self._temp.create(uid, name)

    def open(self, uid, name, flags):
        return self._temp.open(uid, name, flags)

    def release(self, uid, name, fh):
        return self._temp.release(uid, name, fh)

    def _unlink(self, uid, name):
        if self._core:
            self._core.remove(name)

    def unlink(self, uid, name):
        self._vrtx.remove(uid, name)
        self._edge.unlink(uid, name)
        self._attr.unlink(uid, name)
        self._temp.remove(uid, name)
        self._unlink(uid, name)
        self.remove(uid, name)

    def readdir(self, uid, name):
        if not name:
            return self.lsdir(uid, name)
        else:
            return []

    def initialize(self, uid, name):
        f = self.create(uid, name)
        self.release(uid, name, f)

    def discard(self, uid, name):
        return self._temp.discard(uid, name)

    def commit(self, uid, name):
        return self._temp.commit(uid, name)
Exemple #15
0
def run(delay, sensor_type, pin, webhook, source, metric_prefix, output,
        format):
    sensor = None
    is_polling = False
    if sensor_type.startswith('DHT'):
        pin = int(pin)
        sensor = Temp(source, metric_prefix, output, sensor_type, pin, format)
        is_polling = True
    elif sensor_type == 'HC-SRO':
        pins = pin.split(',')
        sensor = Distance(source, metric_prefix, output, sensor_type,
                          int(pins[0]), int(pins[1]), format)
        is_polling = True
    elif sensor_type == 'SSM-1':
        pin = int(pin)
        sensor = Generic(source, metric_prefix, output, sensor_type, pin,
                         'Sound')
    elif sensor_type == 'HC-SR501':
        pin = int(pin)
        sensor = Motion(source, metric_prefix, output, sensor_type, pin)
    elif sensor_type == 'SEO53':
        pin = int(pin)
        sensor = Generic(source, metric_prefix, output, sensor_type, pin,
                         'Vibration')
    elif sensor_type == 'SEO23':
        pin = int(pin)
        sensor = Generic(source, metric_prefix, output, sensor_type, pin,
                         'Tilt')
    elif sensor_type == 'YL-69':
        pin = int(pin)
        sensor = Moisture(source, metric_prefix, output, sensor_type, pin,
                          'Moisture', delay)
    else:
        sensor = Host(source, metric_prefix, output)
        is_polling = True

    while True:
        sensor.get_info()
        metrics = sensor.format_metrics()
        if webhook is not None:
            send_metrics(metrics, output, webhook, source)
        else:
            print(metrics)
        # check if the senor is something that needs to poll for results based on a delay.
        if is_polling:
            time.sleep(delay)
Exemple #16
0
class Attr(Entry):
    def __init__(self, router=None, core=None, rdonly=True):
        Entry.__init__(self, router, core)
        self._temp = Temp(self, rdonly)

    def _log(self, text):
        if LOG_ATTR:
            log_debug(self, text)

    def may_update(self, flags):
        return flags & os.O_APPEND or flags & os.O_RDWR or flags & os.O_TRUNC or flags & os.O_WRONLY

    def can_invalidate(self):
        return True

    def truncate(self, uid, name, length):
        if not self._core:
            path = self.get_path(uid, name)
            self._fs.truncate(uid, path, length)
            self._temp.truncate(uid, name, length)

    def is_expired(self, uid, name):
        temp = get_temp(self.get_path(uid, name))
        return self._fs.exist(uid, temp)

    def getattr(self, uid, name):
        return self.lsattr(uid, name)

    def create(self, uid, name):
        self.check_path(uid, name)
        return self._temp.create(uid, name)

    def open(self, uid, name, flags):
        if self._core:
            flags = 0
        return self._temp.open(uid, name, flags)

    def release(self, uid, name, fh):
        return self._temp.release(uid, name, fh)

    def _unlink(self, uid, name):
        if not self._core:
            return
        child = self.child(name)
        parent = self.parent(name)
        if parent != child:
            if child == ATTR_HANDLER:
                self._core.remove_handler(parent)
            elif child == ATTR_FILTER:
                self._core.remove_filter(parent)
            elif child == ATTR_DISPATCHER:
                self._core.remove_dispatcher(parent)
            elif child == ATTR_MODE:
                self._core.remove_mode(parent)
            elif child == ATTR_FREQ:
                self._core.remove_freq(parent)
            elif child == ATTR_TIMEOUT:
                self._core.remove_timeout(parent)

    def unlink(self, uid, name):
        self.remove(uid, name)
        self._unlink(uid, name)

    def invalidate(self, uid, name):
        self._log('invalidate, name=%s' % str(name))
        path = self.get_path(uid, name)
        temp = get_temp(path)
        if self._fs.exist(uid, path):
            self._fs.rename(uid, path, temp)
            self._unlink(uid, name)
        else:
            self._fs.touch(uid, temp)

    def signature(self, uid, name):
        res = ''
        if RSYNC:
            temp = get_temp(self.get_path(uid, name))
            with open(temp, 'rb') as f:
                sigature = librsync.signature(f)
            res = b64encode(sigature.read())
        return res

    def patch(self, uid, name, buf):
        if not buf:
            log_warnning(self, 'cannot patch, no content, name=%s' % str(name))
            return
        dest = self.get_path(uid, name)
        src = get_temp(dest)
        tmp = b64decode(buf)
        if RSYNC:
            delta = StringIO(tmp)
            with open(dest, 'wb') as f_dest:
                with open(src, 'rb') as f_src:
                    try:
                        librsync.patch(f_src, delta, f_dest)
                    except:
                        log_warnning(self, 'failed to patch, name=%s' % str(name))
                        self._fs.rename(uid, src, dest)
                        return
            self._fs.remove(uid, src)
        else:
            with open(src, 'wb') as f:
                f.write(tmp)
            self._fs.rename(uid, src, dest)

    def readdir(self, uid, name):
        return self.lsdir(uid, name)

    def _create_attr(self, uid, name, attr, val):
        error = False
        name = os.path.join(name, attr)
        f = self.create(uid, name)
        try:
            os.write(f, str(val))
        except:
            error = True
        finally:
            os.close(f)

        if error:
            self.discard(uid, name)
            return

        self.commit(uid, name)

    def initialize(self, uid, name, attr, val):
        if attr not in ATTRIBUTES:
            log_err(self, 'failed to initialize, invalid attribute %s, name=%s' % (str(attr), str(name)))
            raise Exception(log_get(self, 'failed to initialize'))
        if attr == ATTR_PROFILE:
            val = json.dumps(val)
        self._create_attr(uid, name, attr, val)

    def discard(self, uid, name):
        return self._temp.discard(uid, name)

    def commit(self, uid, name):
        return self._temp.commit(uid, name)
Exemple #17
0
 def __init__(self, router=None, core=None, rdonly=True):
     Entry.__init__(self, router, core)
     self._temp = Temp(self, rdonly)
Exemple #18
0
#!/usr/bin/env python
import time
import eeml
from temp import Temp

# COSM variables. API_KEY and FEED are specific
API_KEY = 'SCf8E2SZG3W68pbyUuf1qzg9umMWy6VCkHoeVuuDPEjI2SPN'
FEED = '2053937525'
API_URL = '/v2/feeds/{feednum}.xml' .format(feednum = FEED)

#replace 28-00000449ef31 below with the id of your temperature probe
sensor1=Temp(fileName='28-000004d93f9d')
sensor2=Temp(fileName='28-000004d9ad58')
sensor1.start()
sensor2.start()

#the rest of your code is below.
# The Temp class will be updating on its own thread which will allow you to do
#  anything you want on the main thread.
while True:

        temp1 =  sensor1.getCurrentTemp()
        temp2 = sensor2.getCurrentTemp()

        print temp1
        print temp2

        #open cosm feed
        pac = eeml.Pachube(API_URL, API_KEY)

        #send fahrenheit data