Exemple #1
0
def temperature():
    CLK = 25
    DO = 18
    CS1 = 24
    CS2 = 23

    sensor1 = MAX31855.MAX31855(CLK, CS1, DO)
    sensor2 = MAX31855.MAX31855(CLK, CS2, DO)

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

    return {'Bearing': temp1, 'Motor': temp2}
def temperature():
    # Raspberry Pi software SPI configuration.
    CLK = 25
    CS1 = 23
    CS2 = 24
    DO = 18
    sensor1 = MAX31855.MAX31855(CLK, CS1, DO)
    sensor2 = MAX31855.MAX31855(CLK, CS2, DO)
    temp1 = sensor1.readTempC()
    internal1 = sensor1.readInternalC()
    temp2 = sensor2.readTempC()
    internal2 = sensor2.readInternalC()
    #print('Thermocouple Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, c_to_f(temp)))
    return temp1, temp2
Exemple #3
0
    def __init__(self, spi, tempSensorId, clk=None, cs=None, do=None):
        if spi == "hardware":
            # Raspberry Pi hardware SPI configuration.
            SPI_PORT = 0
            SPI_DEVICE = 0
            self.sensor = MAX31855.MAX31855(
                spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
        elif spi == "gpio":
            self.sensor = MAX31855.MAX31855(clk, cs, do)
        else:
            print "ABORT!!!"

        self.tempSensorId = tempSensorId
        self.sensorNum = TempMAX31855.numSensor
        TempMAX31855.numSensor += 1
        print("Constructing MAX31855 sensor %s" % (tempSensorId))
Exemple #4
0
def readTemp():
    global tEngHist
    #	global tIntHist
    global tEngine
    global tInternal
    tEngArr = []
    tIntArr = []
    counter = 0
    engCounter = 0
    intCounter = 0
    t = 0
    CLK = 5
    CS = 23
    DO = 18
    tempSensor = MAX31855.MAX31855(CLK, CS, DO)
    while True:
        tEngineNow = tempSensor.readTempC()
        if (tEngineNow == tEngineNow):
            tEngArr.append(tEngineNow)
            engCounter += 1
        tInternalNow = tempSensor.readInternalC()
        if (tInternalNow == tInternalNow):
            tIntArr.append(tInternalNow)
            intCounter += 1
        counter += 1
        if (tEngineNow == tEngineNow):
            tEngine = tEngineNow
        if (counter == 60):
            if (engCounter > 0):
                tEngine = sum(tEngArr) / engCounter
            if (intCounter > 0):
                tInternal = sum(tIntArr) / intCounter
            if (tEngine < 0):
                tEngHist.append((t + 2, 53))
            elif (tEngine > 800):
                tEngHist.append((t + 2, 53 - 20))
            else:
                tEngHist.append((t + 2, 53 - 20 * (tEngine / 800)))
#			if (tInternal < 0):
#				tIntHist.append((t + 65, 53))
#			elif (tInternal > 50):
#				tIntHist.append((t + 65, 53 - 20))
#			else:
#				tIntHist.append((t + 65, 53 - 20*(tInternal/50)))
            t += 1
            tEngArr = []
            tIntArr = []
            engCounter = 0
            intCounter = 0
            counter = 0
            if (len(tEngHist) > 124):
                del tEngHist[0]
                tEngHist = setArrayTime(2, tEngHist)


#			if (len(tIntHist) > 60):
#				del tIntHist[0]
#				tIntHist = setArrayTime(65, tIntHist)
        sleep(0.5)
Exemple #5
0
def temperature():
	# Raspberry Pi software SPI configuration.
    CLK = 25
    CS  = 24
    DO  = 18
    sensor = MAX31855.MAX31855(CLK, CS, DO)
    temp = sensor.readTempC()
    internal = sensor.readInternalC()
    #print('Thermocouple Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, c_to_f(temp)))
    return temp
def getTC2Data():
    CLK = 22
    CS = 27
    DO = 17
    sensor = MAX31855.MAX31855(CLK, CS, DO)
    temp = sensor.readTempC()
    internal = sensor.readInternalC()
    tempf = c_to_f(temp)
    internalf = c_to_f(internal)

    return tempf, internalf
    def __init__(self, logging_period):
        __clk_pin = 17
        __cs_pin = 27
        __do_pin = 22

        # logging period is provided in seconds
        self.logging_period = logging_period

        self.sensor = MAX31855.MAX31855(__clk_pin, __cs_pin, __do_pin)

        self.current_reading = ''
Exemple #8
0
    def __init__(self, PLOTSEC=600, outfname='stripchartTemp'):
        self.PLOTSEC = 10  #PLOTSEC #720 # 12 minute sessions for x axis
        self.QUITS = ("q", "Q")
        self.STARTIN = ('I', 'i')
        self.ENDIN = ('E', 'e')
        # Uncomment one of the blocks of code below to configure your Pi or BBB to use
        # software or hardware SPI.
        # Raspberry Pi software SPI configuration.
        #CLK = 25
        #CS  = 24
        #DO  = 18
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # Raspberry Pi hardware SPI configuration.
        self.SPI_PORT = 0
        self.SPI_DEVICE = 0
        self.sensor = MAX31855.MAX31855(
            spi=SPI.SpiDev(self.SPI_PORT, self.SPI_DEVICE))
        # BeagleBone Black software SPI configuration.
        #CLK = 'P9_12'
        #CS  = 'P9_15'
        #DO  = 'P9_23'
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # BeagleBone Black hardware SPI configuration.
        #SPI_PORT   = 1
        #SPI_DEVICE = 0
        #sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

        self.ts = self.getTempStream()
        self.outf = open('%s.xls' % outfname, 'w')
        self.savepng = '%s.png' % outfname
        self.outf.write('Second\tTemperature\n')
        # set up a generator for PLOTSEC seconds of sampling
        style.use('ggplot')
        # prepopulate arrays to make updates quicker
        self.t = range(self.PLOTSEC + 2)
        self.y = [None for i in self.t]
        self.fig, self.ax = plt.subplots()
        #self.ax.set_xlim(auto=True)
        #self.ax.set_ylim(auto=True)

        # fig.canvas.mpl_connect('key_press_event', press)
        self.line, = self.ax.plot(0, 0, lw=1)
        self.text_template = 'Last temperature = %3.2f'
        self.title_template = 'Temperature strip chart at %d seconds'
        self.t_temp = self.ax.text(0.15,
                                   0.15,
                                   self.text_template % (0),
                                   transform=self.ax.transAxes,
                                   family='monospace',
                                   fontsize=10)
        #self.t_title = self.ax.text(0.5,1.0,self.title_template%(0),
        #                            transform=self.ax.transAxes, family='monospace',fontsize=20)
        self.started = time.time()
Exemple #9
0
 def __init__(self, CLK, CS, DO):
     Thread.__init__(self)
     self.CLK = CLK
     self.CS = CS
     self.DO = DO
     self.val = 0
     self.modif = 0
     self.valide = 0
     self.dont_stop = 1
     self.lastT = []
     self.mm = 0
     self.sensor = MAX31855.MAX31855(self.CLK, self.CS, self.DO)
    def init(self):
        # Hardware configuration:
        try:
            # Create an MAX31855 instance.
            self.MAX31855 = MAX31855.MAX31855(spi=SPI.SpiDev(0, self.ce))
        except Exception as e:
            print("MAX31855Config: Error initialising device - exit")
            print(str(e))
            sys.exit(1)

        # provide configuration parameters
        self.ChanNams = ['MAX31855']
Exemple #11
0
    def __init__(self, clk, cs, do, testing=False):
        super(MAX31855Sensor, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.max31855")
        self._temperature = None
        self._temperature_die = None

        self.clk = clk
        self.cs = cs
        self.do = do

        if not testing:
            import Adafruit_MAX31855.MAX31855 as MAX31855
            self.sensor = MAX31855.MAX31855(clk, cs, do)
Exemple #12
0
def temperature():
    # Raspberry Pi software SPI configuration.
    CLK = 25
    CS = 24
    DO = 18
    sensor = MAX31855.MAX31855(CLK, CS, DO)
    temp = sensor.readTempC()
    if np.isnan(temp) == True:
        temp = None
    else:
        pass

    return temp
Exemple #13
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        if not testing:
            import Adafruit_MAX31855.MAX31855 as MAX31855

            self.pin_clock = input_dev.pin_clock
            self.pin_cs = input_dev.pin_cs
            self.pin_miso = input_dev.pin_miso
            self.sensor = MAX31855.MAX31855(self.pin_clock, self.pin_cs,
                                            self.pin_miso)
Exemple #14
0
    def __init__(self, input_dev, testing=False):
        super(MAX31855Sensor, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.max31855")
        self._temperature = None
        self._temperature_die = None

        if not testing:
            import Adafruit_MAX31855.MAX31855 as MAX31855
            self.logger = logging.getLogger(
                "mycodo.inputs.max31855_{id}".format(id=input_dev.id))
            self.pin_clock = input_dev.pin_clock
            self.pin_cs = input_dev.pin_cs
            self.pin_miso = input_dev.pin_miso
            self.convert_to_unit = input_dev.convert_to_unit
            self.sensor = MAX31855.MAX31855(self.pin_clock, self.pin_cs,
                                            self.pin_miso)
Exemple #15
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.setup_logger(testing=testing, name=__name__, input_dev=input_dev)

        if not testing:
            import Adafruit_MAX31855.MAX31855 as MAX31855

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.pin_clock = input_dev.pin_clock
            self.pin_cs = input_dev.pin_cs
            self.pin_miso = input_dev.pin_miso
            self.sensor = MAX31855.MAX31855(self.pin_clock, self.pin_cs,
                                            self.pin_miso)
Exemple #16
0
def temperatureloop():
    # Raspberry Pi software SPI configuration.
    CLK = 25
    DO = 18
    #Comms pin for TCs
    CS = 4, 17, 27, 22
    lst = []

    for i in CS:
        sensor = MAX31855.MAX31855(CLK, i, DO)
        temp = sensor.readTempC()
        if np.isnan(temp) == True:
            temp = None
        lst.append(temp)

    return lst
def main():
    # Get bus address if provided or use default address
    SPI_DEVICE = 0
    if len(sys.argv) >= 2:
        SPI_DEVICE = int(sys.argv[1], 0)

    if not 0 <= SPI_DEVICE <= 1:
        raise ValueError("Invalid address value")

# Raspberry Pi hardware SPI configuration.
    SPI_PORT = 0
    sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

    temp = sensor.readTempC()

    print('{0:0.1f}'.format(temp))
Exemple #18
0
def senseTemperatures():
    sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
    timeStart = time.time()
    transmitter = TransmitterSingleSocket()
    try:
        while True:
            timeNow = time.time()
            timeVal = timeNow - timeStart
            tempInC = sensor.readTempC()
            internalTempInC = sensor.readInternalC()
            transmitter.sendDataPoint(SENSOR_TC, timeVal, tempInC)
            transmitter.sendDataPoint(SENSOR_INTERNAL, timeVal,
                                      internalTempInC)
            time.sleep(0.05)
    except KeyboardInterrupt:
        transmitter.signalEnd()
        transmitter.close()
def termo(q2, q):

    CONSECUTIVO = 0

    CLK = 25
    CS = 24
    DO = 18
    sensor = MAX31855.MAX31855(CLK, CS, DO)

    mariadb_connection = mariadb.connect(user='******',
                                         password='******',
                                         database='SENSORS')
    cursor = mariadb_connection.cursor()

    cont_to_store = 0

    while True:
        temp = sensor.readTempC() - 30
        #print('Thermocouple Temperature: {0:0.3F}*C '.format(temp))
        q2.put(temp)
        #q.get()
        time.sleep(1)
        cont_to_store = cont_to_store + 1
        if cont_to_store == 60:
            try:
                cursor.execute(
                    "INSERT INTO temperature (consecutive, temperature_hot, temperature_cold) VALUES (%s, %s,%s)",
                    (CONSECUTIVO, temp, ceil(q.get() * 100) / 100))
                mariadb_connection.commit()
                #print "The last inserted id was: ", cursor.lastrowid
                #cursor.execute("INSERT INTO employees (first_name,last_name) VALUES (%s,%s)", ('Maria','DB'))
                #INSERT INTO products_tbl (product_name,product_manufacturer) VALUES ('6789','Orbitron 4010')", ('6789','Orbitron 4010')
            except mariadb.Error as error:
                print("Error: {}".format(error))
            cont_to_store = 0

            myFile = open('/home/pi/SENSORS.csv', 'a')
            with myFile:
                writer = csv.writer(myFile)
                myData = [[
                    CONSECUTIVO, temp,
                    ceil(q.get() * 100) / 100,
                    time.strftime("%x") + " " + time.strftime("%X")
                ]]
                writer.writerows(myData)
Exemple #20
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.max31855")

        if not testing:
            import Adafruit_MAX31855.MAX31855 as MAX31855
            self.logger = logging.getLogger("mycodo.max31855_{id}".format(
                id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.pin_clock = input_dev.pin_clock
            self.pin_cs = input_dev.pin_cs
            self.pin_miso = input_dev.pin_miso
            self.sensor = MAX31855.MAX31855(self.pin_clock, self.pin_cs,
                                            self.pin_miso)
Exemple #21
0
def main(web_output_file, interval, web_server_port, verbose, log_interval,
         output_file_pattern, output_separator, log_short_interval,
         short_interval, short_output_file_pattern):
    '''Interval is in minutes. Short_interval is seconds.
    '''

    # Hardware configuration is set at top of file
    global CLK, DO, CS

    # Setup
    output_file = None
    log_interval = datetime.timedelta(minutes=log_interval)
    file_start_time = None  # For logging hours since start of file
    interval_start_time = None
    web_server = subprocess.Popen(
        ['python', '-m', 'SimpleHTTPServer',
         str(web_server_port)],
        cwd=os.path.dirname(web_output_file))

    if log_short_interval:
        short_output_file = None
        short_interval = datetime.timedelta(seconds=short_interval)
        short_file_start_time = None  # For logging hours since start of file
        short_interval_start_time = None

    print('About to connect to %i sensors' % len(CS))
    sensors = [MAX31855.MAX31855(CLK, this_CS, DO) for this_CS in CS]
    print('Sensors connected')
    while True:
        try:
            # Collect the data
            temps = [sensor.readAll() for sensor in sensors]
            for t in temps:
                for k in t.keys():
                    if k != 'state':
                        t[k] = c_to_f(t[k])
            now = datetime.datetime.now()

            # Stdout output
            if verbose:
                print(now.isoformat() + ' ' + '; '.join([
                    '%.2f,%.2f,%.2f' %
                    (t['temp'], t['internal'], t['linearized']) for t in temps
                ]))

            # Html output
            # Always overwrite current file
            html = '<html><head><meta http-equiv="refresh" content="1"><title>Current Temps</title></head>'
            lines = [
                '%s: %.1f F' % (name, t['linearized'])
                for name, t in zip(SENSOR_NAMES, temps)
            ]
            lines += ['<br>', '<br>']
            lines += [
                '%s: %.1f internal; errors: %s' %
                (name, t['internal'],
                 str([s for s, v in t['state'].items() if v]))
                for name, t in zip(SENSOR_NAMES, temps)
            ]
            html += '<body><h1>%s<br><<%s></h1></body></html>' % (
                '<br>'.join(lines), now.isoformat())
            with open(web_output_file, 'w') as web_file:
                web_file.write(html)

            # Log file output
            if not interval_start_time:
                interval_start_time = now
            if log_short_interval:
                if not short_interval_start_time:
                    short_interval_start_time = now

            if (not file_start_time) or (now - interval_start_time >=
                                         log_interval):
                if not file_start_time:
                    file_start_time = now
                # Assemble data dictionary
                data_dict = OrderedDict([
                    ('timestamp', now.strftime('%H:%M:%S')),
                    ('hours',
                     format((now - file_start_time).total_seconds() / 3600.0,
                            '06.3f'))
                ])
                data_dict.update([('%s F' % name,
                                   format(t['linearized'], '.2f'))
                                  for name, t in zip(SENSOR_NAMES, temps)])
                data_dict.update([('internal %s F' % name,
                                   format(t['internal'], '.2f'))
                                  for name, t in zip(SENSOR_NAMES, temps)])
                # Write out the data
                if not output_file or now.date() != current_date:
                    if output_file:
                        output_file.close()
                    print('Opening new output file')
                    current_date = datetime.datetime.now().date()
                    output_file = get_output_file(
                        current_date.strftime(output_file_pattern), data_dict,
                        output_separator)
                output_file.write(
                    output_separator.join([str(x)
                                           for x in data_dict.values()]) +
                    '\n')
                interval_start_time = now

            if log_short_interval:
                if (not short_file_start_time) or (
                        now - short_interval_start_time >= short_interval):
                    if not short_file_start_time:
                        short_file_start_time = now
                    # Assemble data dictionary
                    data_dict = OrderedDict([
                        ('timestamp', now.strftime('%H:%M:%S')),
                        ('hours',
                         format((now - short_file_start_time).total_seconds() /
                                3600.0, '07.4f'))
                    ])
                    data_dict.update([('%s F' % name,
                                       format(t['linearized'], '.2f'))
                                      for name, t in zip(SENSOR_NAMES, temps)])
                    # Write out the data
                    if not short_output_file or now.date() != current_date:
                        if short_output_file:
                            short_output_file.close()
                        print('Opening new short output file')
                        current_date = datetime.datetime.now().date()
                        short_output_file = get_output_file(
                            current_date.strftime(short_log_file_pattern),
                            data_dict, output_separator)
                    short_output_file.write(
                        output_separator.join(
                            [str(x) for x in data_dict.values()]) + '\n')
                    short_interval_start_time = now

            time.sleep(interval - time.time() % interval)  # corrects for drift

        except KeyboardInterrupt:
            break

    web_server.terminate()  # Cleanup
Exemple #22
0
    levelAlarmSent = False

    # Set term and int signals to be ignored - passed to child processes
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    signal.signal(signal.SIGTERM, signal.SIG_IGN)

    # Import multiprocess functions <enforces simple context>
    import ThermoPiMP

    # Create Thermocouple reader objects
    CLK = 24
    SO = 10
    CS1 = 9
    CS2 = 11

    T1 = mx3.MAX31855(CLK, CS1, SO)  # Sensor 1, placed below the LN fill line
    T2 = mx3.MAX31855(CLK, CS2, SO)  # Sensor 2, placed near the top plug

    # Define globals for current readings
    temp1 = 0
    inter1 = 0
    temp2 = 0
    inter2 = 0
    states = ['openCircuit', 'shortGND', 'shortVCC', 'fault']
    state1 = [True, True, True, True]
    state2 = [True, True, True, True]
    counter = 0
    linearizeTemps = True

    alarmCondition = 0
Exemple #23
0
class Heater:

    desired_temp = None  # Fully populated once constructed
    current_step = 0  # Track which iteration we are on
    temperature_readings = [0]  # Add to list as we step
    errors = [0]  # Add to this as we step
    current_temperature = 0  # Updated in step()

    if on_pi_hardware:
        # Raspberry Pi software SPI configuration. (For thermocouple)
        CLK = 25
        CS = 24
        DO = 18
        sensor = MAX31855.MAX31855(CLK, CS, DO)

        # Raspberry Pi hardware SPI configuration. (For thermocouple)
        # SPI_PORT = 0
        # SPI_DEVICE = 0
        # sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=5000000))

        i2c = busio.I2C(board.SCL, board.SDA)
        dac = adafruit_mcp4725.MCP4725(i2c)

    # Calculates the temperature based on dni_arr and secs_per_cycle
    def __init__(self, dni_arr, secs_per_cycle):
        self.mutex = Lock()

        # sample every secs_per_cycle since this probably won't run every second
        desired_temp = dni_arr[::secs_per_cycle]

        # multiply by 2 for some reason
        desired_temp = np.multiply(desired_temp, 2)

        # v = (5 / 208) * (DNI) / sqrt(DNI / R)(on each element in the list)
        R = 15
        voltage_ratio = 5 / 208  # The ratio of the analog control voltage to max voltage into the heater

        for i in range(0, len(desired_temp)):
            desired_temp[i] = voltage_ratio * desired_temp[i] / math.sqrt(
                desired_temp[i] / R)

        # desired_temp = 8.6*v^2 + 115v (on each element in the list)
        # Estimated calibration equation, analog voltage to Celsius
        for i in range(0, len(desired_temp)):
            desired_temp[i] = 8.6 * math.pow(desired_temp[i],
                                             2) + 115 * desired_temp[i]

        self.desired_temp = desired_temp
        print("DEBUG: [Heater] Constructed")

    # public facing step method
    # spawns a thread and calls the synchronous step_sync helper method
    def step(self):
        print("DEBUG: [Heater] Stepping")
        t1 = Thread(target=self.__step_sync)
        t1.start()

    # private synchronous helper method that runs each time we need to check heater temp
    def __step_sync(self):

        # Stop stepping once we have reached the end of the desired_temp array
        # (for the case where the desired_temp arr is not evenly divisible by secs_per_cycle
        if self.current_step >= len(self.desired_temp) - 1:
            return
        else:
            self.current_step += 1
        if not on_pi_hardware:
            return
        self.mutex.acquire()
        print("DEBUG: [Heater] Stepping for", self.current_step)

        # Read the current temperature
        current_temp = self.sensor.readTempC()
        self.current_temperature = current_temp

        # Calculate the control temperature
        kP = 1000
        ki = 10
        kd = 25

        # control_temperature = desired_temp_c[currentsecond] + kP * error[current reading and current desired
        # temperature] + ki * [sum of all errors] + kd * (this error - previous error)
        ref_temp = self.desired_temp[self.current_step]
        error = ref_temp - current_temp
        control_temperature = ref_temp + kP * error + ki * np.sum(
            self.errors) + kd * self.errors[len(self.errors) - 1]
        self.errors.append(error)

        # convert control temperature to voltage
        control_voltage = 500 * control_temperature

        # actual dac output (0-4096)
        actual_dac_output = control_voltage / 5 * 4096

        if actual_dac_output > 4096:
            actual_dac_output = 4096
        elif actual_dac_output < 0:
            actual_dac_output = 0

        self.dac.set_voltage(actual_dac_output)

        print("DEBUG: [Heater] Done stepping for", self.current_step)

        self.mutex.release()

    # returns the state of this stepper motor
    def get_state(self):
        return {
            "current_temperature": str(self.current_temperature),
            "reference_temperature": str(self.desired_temp[self.current_step])
        }

    def get_desired_temp_arr(self):
        return self.desired_temp.tolist()
Exemple #24
0
class ToasterController(object):

    loaded = False
    instructions = None
    timer = None
    cancel = False
    spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
    cs = digitalio.DigitalInOut(board.D5)
    max31855 = adafruit_max31855.MAX31855(spi, cs)
    main_time = 12
    cancel_time = 1
    #motor1 = Motor(forward = 2, backward = 4)

    CLK = 11
    CS = 8
    DO = 9
    sensor = MAX31855.MAX31855(CLK, CS, DO)

    btn = Button(27)
    button_1_channel = 22
    button_2_channel = 27
    button_3_channel = 17

    def c_to_f(c):
        return c * 9.0 / 5.0 + 32.0

    def __init__(self, instructions):
        self.instructions = instructions
        self.timer = CookTimer()

    def start(self, c, motor1):
        ''' Begin cooking '''
        self.timer.set(self.instructions.cook_time)
        self.lower_platform(c, motor1)

    def lower_platform(self, c, motor1):
        try:
            self.loaded = True
            for x in range(0, self.main_time, 1):
                motor1.backward()
                if self.cancel == True:
                    break
                note = 'Lowering food...'
                c.send(note.encode('utf-8'))
                print('Main: ', self.main_time)
                print('Cancel: ', self.cancel_time)
                self.cancel_time = self.cancel_time + 1
                time.sleep(1)
            if self.cancel == False:
                note = 'Food Lowered' + ' '
                c.sendall(note.encode('utf-8'))
                print("Platform is lowered")
                motor1.stop()
                self.timer.start()
                self.wait_time(c, self.instructions)
        except OSError:
            print("Error...")
            motor1.stop()

    def lower_platform_offline(self, motor1):
        try:
            self.loaded = True
            for x in range(0, self.main_time, 1):
                motor1.backward()
                if self.cancel == True:
                    break
                print('Main: ', self.main_time)
                print('Cancel: ', self.cancel_time)
                self.cancel_time = self.cancel_time + 1
                time.sleep(1)
            if self.cancel == False:
                print("Platform is lowered")
                motor1.stop()
                self.timer.start()
                self.wait_time_offline(self.instructions)
        except OSError:
            print("Error...")
            motor1.stop()

    def wait_time(self, c, instructions):
        '''Send data to app'''
        if int(self.timer.remaining_time) <= 0:
            self.timer.cook_time = instructions.cook_time
        try:
            for x in range(int(self.timer.remaining_time), -1, -1):
                if self.cancel == True:
                    break
                print(self.timer.remaining_time)
                time_split = str(round(self.timer.remaining_time))
                tempC = self.sensor.readTempC()
                tempF = str(tempC * 9 / 5 + 32)
                print('Temperature: {} C {} F '.format(tempC, tempF))
                total_data = time_split + ' ' + tempF + ' ' + 'Code'
                c.send(total_data.encode('utf-8'))
                instructions.stopped.wait(timeout=1)
        except OSError:
            print("Error...")

    def wait_time_offline(self, instructions):
        '''Send data to app'''
        if int(self.timer.remaining_time) <= 0:
            self.timer.cook_time = instructions.cook_time
        try:
            for x in range(int(self.timer.remaining_time), -1, -1):
                if self.cancel == True:
                    break
                print(self.timer.remaining_time)
                instructions.stopped.wait(timeout=1)
        except OSError:
            print("Error...")
            motor1.stop()

    def raise_platform(self, c, motor1):
        try:
            self.loaded = False
            raise_time = -1
            self.cancel_time = self.cancel_time - 1
            print('Main: ', self.main_time)
            print('Cancel: ', self.cancel_time)
            if self.main_time != self.cancel_time:
                raise_time = raise_time + self.cancel_time + 1
            else:
                raise_time = self.main_time
            for x in range(0, raise_time, 1):
                motor1.forward()
                note = 'Raising food...'
                c.send(note.encode('utf-8'))
                time.sleep(1)
            note = 'Raised'
            c.send(note.encode('utf-8'))
            print("Platform is raised")
            motor1.stop()
        except OSError:
            print("Error...")
            motor1.stop()

    def raise_platform_offline(self, motor1):
        try:
            self.loaded = False
            raise_time = -1
            print('Main: ', self.main_time)

            if self.main_time != self.cancel_time:
                raise_time = raise_time + self.cancel_time
            else:
                raise_time = self.main_time
            print('Raise: ', raise_time)
            for x in range(0, raise_time, 1):
                motor1.forward()
                time.sleep(1)
            print("Platform is raised")
            motor1.stop()
        except OSError:
            print("Error...")
            motor1.stop()

    def reset(self):
        '''reset timer mid cook'''
        self.cancel = False
        self.timer.clear()

    def end(self, c, motor1):
        ''' Cooking has finished '''
        self.cancel = False
        self.timer.clear()
        self.instructions.clear()
        self.raise_platform(c, motor1)
        self.cancel_time = 0

    def end_offline(self, motor1):
        ''' Cooking has finished '''
        self.cancel = False
        self.timer.clear()
        self.instructions.clear()
        self.raise_platform_offline(motor1)
        self.cancel_time = 0
Exemple #25
0
from device import heater
from interface import APIInterface
from device import thermometer
import Adafruit_MAX31855.MAX31855 as MAX31855
import RPi.GPIO as GPIO

# Disable the temperature probe logger because it produces annoying and useless messages
maxlog = logging.getLogger('Adafruit_MAX31855.MAX31855')
maxlog.disabled = True

# Set up a logger for application notifications and errors
log = logging.getLogger("heater")

# We use rotating log files so that if there is a crash mid-run, we will lose the least amount possible.
# 5120 bytes is around 50 lines of log messages
handler = RotatingFileHandler('/var/log/piwarmer/heater.log',
                              maxBytes=5120,
                              backupCount=10000)
formatter = logging.Formatter(
    '%(asctime)s\t%(name)s\t%(levelname)s\t\t%(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.DEBUG)

if __name__ == "__main__":
    api_interface = APIInterface()
    thermometer = thermometer.Thermometer(MAX31855.MAX31855(24, 23, 18))
    heater = heater.Heater(GPIO)
    with ProgramRunner(api_interface, thermometer, heater) as program:
        program.run()
Exemple #26
0
 def __init__(self, temp_unit=DEGREES_F):
     BaseSensor.__init__(self, temp_unit=temp_unit)
     self.sensor = MAX31855.MAX31855(self.CLK, self.CS, self.DO)
Exemple #27
0
import Adafruit_MAX31855.MAX31855 as MAX31855


# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
    return c * 9.0 / 5.0 + 32.0


# Uncomment one of the blocks of code below to configure your Pi or BBB to use
# software or hardware SPI.

# Raspberry Pi software SPI configuration.
CLK = 25
CS = 24
DO = 18
sensor = MAX31855.MAX31855(CLK, CS, DO)

# Raspberry Pi hardware SPI configuration.
#SPI_PORT   = 0
#SPI_DEVICE = 0
#sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

# BeagleBone Black software SPI configuration.
#CLK = 'P9_12'
#CS  = 'P9_15'
#DO  = 'P9_23'
#sensor = MAX31855.MAX31855(CLK, CS, DO)

# BeagleBone Black hardware SPI configuration.
#SPI_PORT   = 1
#SPI_DEVICE = 0
    except:
        result['fail'] = 'none configured'
    return jsonify(result)

@app.route('/getaplist')
def getAPList():

    APlist = []
    cells = wifi.Cell.all('wlan0')
    for cell in cells:
        APlist.append(cell.ssid)
    print(APlist)
    return jsonify(aplist=APlist)

if __name__ == '__main__':
    try:

        SPI_PORT   = 0
        SPI_DEVICE = 0
        sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

        controller = Controller()
        loadSetting()
        app.run(host='0.0.0.0', port=80, debug=False, threaded=True)

    except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
        pass
    finally:
        controller.event.set()
        time.sleep(2)
Exemple #29
0
 def __init__(self):
     self.sensor = thermocouple = MAX31855.MAX31855(GPIO_THERMOCOUPLE_CLK,
                                                    GPIO_THERMOCOUPLE_CS,
                                                    GPIO_THERMOCOUPLE_DO)
def pid_loop(dummy, state):
    import sys
    from time import sleep, time
    from math import isnan
    import Adafruit_GPIO.SPI as SPI
    import Adafruit_MAX31855.MAX31855 as MAX31855
    import PID as PID
    import config as conf

    def c_to_f(c):
        return c * 9.0 / 5.0 + 32.0

    sensor = MAX31855.MAX31855(spi=SPI.SpiDev(conf.spi_port, conf.spi_dev))

    pid = PID.PID(conf.Pc, conf.Ic, conf.Dc)
    pid.SetPoint = state['settemp']
    pid.setSampleTime(conf.sample_time * 5)

    nanct = 0
    i = 0
    j = 0
    pidhist = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]
    avgpid = 0.
    temphist = [0., 0., 0., 0., 0.]
    avgtemp = 0.
    lastsettemp = state['settemp']
    lasttime = time()
    sleeptime = 0
    iscold = True
    iswarm = False
    lastcold = 0
    lastwarm = 0

    try:
        while True:  # Loops 10x/second
            tempc = sensor.readTempC()
            if isnan(tempc):
                nanct += 1
                if nanct > 100000:
                    sys.exit
                continue
            else:
                nanct = 0

            tempf = c_to_f(tempc)
            temphist[i % 5] = tempf
            avgtemp = sum(temphist) / len(temphist)

            if avgtemp < 100:
                lastcold = i

            if avgtemp > 200:
                lastwarm = i

            if iscold and (i - lastcold) * conf.sample_time > 60 * 15:
                pid = PID.PID(conf.Pw, conf.Iw, conf.Dw)
                pid.SetPoint = state['settemp']
                pid.setSampleTime(conf.sample_time * 5)
                iscold = False

            if iswarm and (i - lastwarm) * conf.sample_time > 60 * 15:
                pid = PID.PID(conf.Pc, conf.Ic, conf.Dc)
                pid.SetPoint = state['settemp']
                pid.setSampleTime(conf.sample_time * 5)
                iscold = True

            if state['settemp'] != lastsettemp:
                pid.SetPoint = state['settemp']
                lastsettemp = state['settemp']

            if i % 10 == 0:
                pid.update(avgtemp)
                pidout = pid.output
                pidhist[i / 10 % 10] = pidout
                avgpid = sum(pidhist) / len(pidhist)

            state['i'] = i
            state['tempf'] = round(tempf, 2)
            state['avgtemp'] = round(avgtemp, 2)
            state['pidval'] = round(pidout, 2)
            state['avgpid'] = round(avgpid, 2)
            state['pterm'] = round(pid.PTerm, 2)
            if iscold:
                state['iterm'] = round(pid.ITerm * conf.Ic, 2)
                state['dterm'] = round(pid.DTerm * conf.Dc, 2)
            else:
                state['iterm'] = round(pid.ITerm * conf.Iw, 2)
                state['dterm'] = round(pid.DTerm * conf.Dw, 2)
            state['iscold'] = iscold

            print time(), state

            sleeptime = lasttime + conf.sample_time - time()
            if sleeptime < 0:
                sleeptime = 0
            sleep(sleeptime)
            i += 1
            lasttime = time()

    finally:
        pid.clear