def _res(self, addr): ow = OneWire(Pin(self.pin)) ow.reset() ow.select_rom(addr) ow.writebyte(0x4E) if self.res == 12: ow.writebyte(0x7F) ow.writebyte(0x7F) ow.writebyte(0x7F) print("12 bit mode") if self.res == 11: ow.writebyte(0x5F) ow.writebyte(0x5F) ow.writebyte(0x5F) print("11 bit mode") if self.res == 10: ow.writebyte(0x3F) ow.writebyte(0x3F) ow.writebyte(0x3F) print("10 bit mode") if self.res == 9: ow.writebyte(0x1F) ow.writebyte(0x1F) ow.writebyte(0x1F) print("9 bit mode") ow.reset()
def __init__(self, pin): if not isinstance(pin, int): raise TypeError("pin must be integer") from onewire import OneWire from ds18x20 import DS18X20 ow = OneWire(machine.Pin(pin)) ow.scan() ow.reset() self.ds18b20 = DS18X20(ow) self.roms = self.ds18b20.scan() self.temps = [None for rom in self.roms]
class TemperatureSensor: class _Const: CONVERT = const(0x44) RD_SCRATCH = const(0xbe) def __init__(self, pin): self._onewire = OneWire(pin) self._buffer = bytearray(9) self._rom = [rom for rom in self._onewire.scan() if rom[0] in (0x10, 0x22, 0x28)][0] self._convert_temp() def _convert_temp(self): self._onewire.reset(True) self._onewire.writebyte(self._onewire.SKIP_ROM) self._onewire.writebyte(self._Const.CONVERT) def _read_scratch(self): self._onewire.reset(True) self._onewire.select_rom(self._rom) self._onewire.writebyte(TemperatureSensor._Const.RD_SCRATCH) self._onewire.readinto(self._buffer) if self._onewire.crc8(self._buffer): raise Exception('Temperature sensor::CRC error') return self._buffer def read(self): buffer = self._read_scratch() if self._rom[0] == 0x10: if self._buffer[1]: t = self._buffer[0] >> 1 | 0x80 t = -((~t + 1) & 0xff) else: t = self._buffer[0] >> 1 return t - 0.25 + (self._buffer[7] - self._buffer[6]) / self._buffer[7] else: t = self._buffer[1] << 8 | self._buffer[0] if t & 0x8000: t = -((t ^ 0xffff) + 1) return t / 16
class TempTester: def __init__(self): print("Init") self.unhandled_event = False print('Init LEDs') self.leds = { 'red': Pin(D2, Pin.OUT, value=False), 'blue': Pin(D3, Pin.OUT, value=False), 'green': Pin(D4, Pin.OUT, value=False) } print('Init OneWire') self.ds_pin = Pin(D1) self.ow_inst = OneWire(self.ds_pin) self.ds_sensor = DS18X20(self.ow_inst) self.temp_id = self.ds_sensor.scan()[0] print('Temperature sensor: %s' % self.temp_id) self.wlan = network.WLAN(network.STA_IF) self.mac = hexlify(self.wlan.config('mac')).decode() print('MAC: %s' % self.mac) def run(self): resp = None while resp != 'x': print('x) exit') print('0) OFF') print('1) red') print('2) green') print('3) blue') print('4) magenta') print('5) cyan') print('6) yellow') print('7) white') print('t) temp') resp = input('Selection: ').strip() if resp == 'x': break elif resp == '0': self.leds['red'].off() self.leds['green'].off() self.leds['blue'].off() elif resp == '1': self.leds['red'].on() self.leds['green'].off() self.leds['blue'].off() elif resp == '2': self.leds['red'].off() self.leds['green'].on() self.leds['blue'].off() elif resp == '3': self.leds['red'].off() self.leds['green'].off() self.leds['blue'].on() elif resp == '4': self.leds['red'].on() self.leds['green'].off() self.leds['blue'].on() elif resp == '5': self.leds['red'].off() self.leds['green'].on() self.leds['blue'].on() elif resp == '6': self.leds['red'].on() self.leds['green'].on() self.leds['blue'].off() elif resp == '7': self.leds['red'].on() self.leds['green'].on() self.leds['blue'].on() elif resp == 't': self.leds['red'].off() self.leds['green'].off() self.leds['blue'].off() self.get_temp() def get_temp(self): print('converting temps...') self.ds_sensor.convert_temp() sleep(1) temp_c = self.ds_sensor.read_temp(self.temp_id) print('temp_c=%s' % temp_c) if temp_c == 85.0: print('Got bad temp; reset onewire bus') self.ow_inst.reset() return temp_f = ((temp_c * 9.0) / 5.0) + 32 print('temp_f=%s' % temp_f) def set_rgb(self, red, green, blue): self.leds['red'].value(red) self.leds['green'].value(green) self.leds['blue'].value(blue) def blink_leds(self, colors, length_ms=250, num_times=1): for color, led in self.leds.items(): if color not in colors: led.off() for idx in range(0, num_times): for color in colors: self.leds[color].on() sleep_ms(length_ms) for color in colors: self.leds[color].off() if idx != num_times - 1: sleep_ms(length_ms)
class TempSender: def __init__(self): printflush("Init") self.unhandled_event = False printflush('Init LEDs') self.leds = { 'red': Pin(D2, Pin.OUT, value=False), 'blue': Pin(D3, Pin.OUT, value=False), 'green': Pin(D4, Pin.OUT, value=False) } printflush('Init OneWire') self.ds_pin = Pin(D1) self.ow_inst = OneWire(self.ds_pin) self.ds_sensor = DS18X20(self.ow_inst) self.temp_id = self.ds_sensor.scan()[0] printflush('Temperature sensor: %s' % self.temp_id) printflush('set LED red') self.leds['red'].on() printflush('Instantiate WLAN') self.wlan = network.WLAN(network.STA_IF) printflush('connect_wlan()') self.connect_wlan() printflush('turn off red LED') self.leds['red'].off() printflush('hexlify mac') self.mac = hexlify(self.wlan.config('mac')).decode() printflush('MAC: %s' % self.mac) self.entity_id = ENTITIES[self.mac] self.friendly_name = FRIENDLY_NAMES[self.mac] printflush('Entity ID: %s; Friendly Name: %s' % ( self.entity_id, self.friendly_name )) self.post_path = '/api/states/' + self.entity_id printflush('POST path: %s' % self.post_path) def run(self): printflush("Enter loop...") while True: self.send_temp() printflush('sleep 60') sleep(60) printflush('after sleep 60') def send_temp(self): printflush('converting temps...') self.ds_sensor.convert_temp() sleep(1) printflush('read_temp()') temp_c = self.ds_sensor.read_temp(self.temp_id) printflush('temp_c=%s' % temp_c) if temp_c == 85.0: printflush('Got bad temp; reset onewire bus') self.ow_inst.reset() return temp_f = ((temp_c * 9.0) / 5.0) + 32 printflush('temp_f=%s' % temp_f) data = json.dumps({ 'state': round(temp_f, 2), 'attributes': { 'friendly_name': self.friendly_name, 'unit_of_measurement': '\u00b0F' } }) self.http_post(data) def connect_wlan(self): self.wlan.active(True) if not self.wlan.isconnected(): printflush('connecting to network...') self.wlan.connect(SSID, WPA_KEY) while not self.wlan.isconnected(): pass printflush('network config:', self.wlan.ifconfig()) def http_post(self, data): printflush('http_post() called') printflush('set LED blue') self.set_rgb(False, False, True) printflush('getaddrinfo()') addr = socket.getaddrinfo(HOOK_HOST, HOOK_PORT)[0][-1] printflush('Connect to %s:%s' % (HOOK_HOST, HOOK_PORT)) s = socket.socket() s.settimeout(10.0) try: printflush('before connect()') s.connect(addr) printflush('after connect()') except OSError as exc: printflush('ERROR connecting to %s: %s' % (addr, exc)) printflush('set LEDs off') self.set_rgb(False, False, False) printflush('blink red LED') self.blink_leds(['red'], num_times=3, length_ms=100) printflush('s.close()') s.close() printflush('CONNECTION ERROR: calling machine.soft_reset()') machine.soft_reset() return None printflush('POST to: %s: %s' % (self.post_path, data)) b = 'POST %s HTTP/1.0\r\nHost: %s\r\n' \ 'Content-Type: application/json\r\n' \ 'Authorization: Bearer %s\r\n' \ 'Content-Length: %d\r\n\r\n%s' % ( self.post_path, HOOK_HOST, HASS_TOKEN, len(bytes(data, 'utf8')), data ) printflush('SEND:\n%s' % b) s.send(bytes(b, 'utf8')) printflush('after send()') buf = '' while True: data = s.recv(100) if data: buf += str(data, 'utf8') else: break printflush('received data:') printflush(buf) s.close() printflush('after close()') self.set_rgb(False, False, False) if 'HTTP/1.0 201 Created' or 'HTTP/1.0 200 OK' in buf: printflush('OK') printflush('blink LED green') self.blink_leds(['green']) else: printflush('FAIL') printflush('blink LED red') self.blink_leds(['red'], num_times=3, length_ms=100) printflush('http_post done') def set_rgb(self, red, green, blue): self.leds['red'].value(red) self.leds['green'].value(green) self.leds['blue'].value(blue) def blink_leds(self, colors, length_ms=250, num_times=1): for color, led in self.leds.items(): if color not in colors: led.off() for idx in range(0, num_times): for color in colors: self.leds[color].on() sleep_ms(length_ms) for color in colors: self.leds[color].off() if idx != num_times - 1: sleep_ms(length_ms)
board = Pysense() light_sensor = LTR329ALS01(board) barometric_pressure = MPL3115A2(board, mode=PRESSURE) # barometric_altitude = MPL3115A2(board, mode=ALTITUDE) humidity_sensor = SI7006A20(board) # ,-----------------------------------------------------------, # | This is the DS18B20 liquid temperature sensor. | # '-----------------------------------------------------------' lts_pin = OneWire(Pin("P10")) # Set up input GPIO. liquid_temp_sensor = DS18X20(lts_pin) # ,-----------------------------------------------------------, # | Now let's see which sensors are attached and working. | # '-----------------------------------------------------------' # DS18B20 lts_ready = lts_pin.reset() logger.info("Liquid temperature sensor present = %s.", lts_ready) # MPL3115A2 barometer_ready = barometric_pressure._read_status() logger.info("Barometer sensor present = %s.", barometer_ready) # ,-----------------------------------------------------------, # | There are no available functions to test the presence of | # | the light or humidity sensors so these are just assumed | # | to be available for now. It should be possible to simply | # | scan the I2C bus at the addresses for each sensor to | # | detect them. | # '-----------------------------------------------------------' # LTR329ALS01
def _request(self, addr): _res(self, addr) ow = OneWire(Pin(self.pin)) ow.reset() ow.select_rom(addr) ow.writebyte(0x44) # command to take reading if self.res == 12: # the resolution determines the amount of time needed time.sleep_ms(1000) if self.res == 11: time.sleep_ms(400) if self.res == 10: time.sleep_ms(200) if self.res == 9: time.sleep_ms(100) ow.reset() # reset required for data ow.select_rom(addr) ow.writebyte(0xBE) # command to send temperature data # all nine bytes must be read LSB = ow.readbyte() # least significant byte MSB = ow.readbyte() # most significant byte ow.readbyte() ow.readbyte() ow.readbyte() # this is the configuration byte for resolution ow.readbyte() ow.readbyte() ow.readbyte() ow.readbyte() ow.reset() # reset at end of data transmission # convert response to binary, format the binary string, and perform math d_LSB = float(0) d_MSB = float(0) count = 0 b = bin(LSB) b2 = bin(MSB) b3 = "" l = 10 - len(b2) for i in range(l): if len(b2) < 10: b3 += "0" b2 = b3 + b2 b4 = "" l = 10 - len(b) for i in range(l): if len(b) < 10: b4 += "0" b5 = b4 + b for i in b5: if count == 2: if i == '1': d_LSB += 2**3 if count == 3: if i == '1': d_LSB += 2**2 if count == 4: if i == '1': d_LSB += 2**1 if count == 5: if i == '1': d_LSB += 2**0 if count == 6: if i == '1': d_LSB += 2**-1 if count == 7: if i == '1': d_LSB += 2**-2 if count == 8: if i == '1': d_LSB += 2**-3 if count == 9: if i == '1': d_LSB += 2**-4 count += 1 count = 0 sign = 1 for i in b2: if count == 6: if i == '1': sign = -1 if count == 7: if i == '1': d_MSB += 2**6 if count == 8: if i == '1': d_MSB += 2**5 if count == 9: if i == '1': d_MSB += 2**4 count += 1 temp = (d_LSB + d_MSB) * sign if self.unit == 'c' or self.unit == 'C': print("TEMP is: " + str(temp) + " degrees C") if self.unit == 'f' or self.unit == 'F': temp = (temp * 9 / 5) + 32 print("TEMP F is: " + str(temp)) return temp