class BTHomeTemperature:
    global thermistor
    objectID = 0x45     # temperature
    
    def __get__(self, obj, objtype=None):
        b = bytearray(3)
        b[0] = self.objectID
        temperature = int(thermistor.temperature * 10)
        b[1] =  temperature & 0xFF
        b[2] = (temperature & 0xFF00) >> 8
        return b

class BTHomeLight:
    objectID = 0x05     # illuminance
    
    def __get__(self, obj, objtype=None):
        b = bytearray(4)
        b[0] = self.objectID
        lux = int(simpleio.map_range(light.value, 0, 65535, 0, 10000) * 100)
        b[3] = (lux & 0xFF0000) >> 16
        b[2] = (lux & 0x00FF00) >> 8
        b[1] = lux & 0x00FF
        return b

class BTHomeSound:
    objectID = 0x2A     # sound - boolean
    # Number of samples to read at once.
    NUM_SAMPLES = 160
    
    
    def __init__(self):
        # Record an initial sample to calibrate. Assume it's quiet when we start.
        self.samples = array.array('H', [0] * self.NUM_SAMPLES)
        mic.record(self.samples, len(self.samples))
    
    def mean(self, values):
        return sum(values) / len(values)
    
    # Remove DC bias before computing RMS.
    def normalized_rms(self, values):
        minbuf = int(self.mean(values))
        samples_sum = sum(
            float(sample - minbuf) * (sample - minbuf)
            for sample in values
        )
        return math.sqrt(samples_sum / len(values))
        
    def get(self):
        mic.record(self.samples, len(self.samples))
        magnitude = self.normalized_rms(self.samples)
        return(magnitude)
        # You might want to print this to see the values.
        # print(magnitude)

class BTHomeButton:
    objectID = 0x3A     # button
    
    def __init__(self, button):
        self.button = button
        self.current_value = button.value
    
    def __get__(self, obj, objtype=None):
        b = bytearray(2)
        b[0] = self.objectID
        if self.button.value != self.current_value:
            if not self.current_value:
                # Button pressed
                self.current_value = True
                b[1] = 0x01
            else:
                # Button released
                self.current_value = False
                b[1] = 0x00
        else:
            b[1] =0x00
        return b
    
class BTHomeAccelerometer:
    objectID = 0x51
    
    def __get__(self, obj, objtype=None):
         b = bytearray(3)
         b[0] = self.objectID
         x,y,z = lis3dh.acceleration
         
         '''
         x = int(abs(x) * 1000)
         b[1] = x & 0x0FF
         b[2] = (x & 0x00FF00) >> 8

         b[3] = self.objectID
         y = int(y * 1000)
         b[4] = y & 0x0FF
         b[5] = (y & 0x00FF00) >> 8
         '''
         b[0] = self.objectID
         z = int(z * 1000)
         b[1] = z & 0x0FF
         b[2] = (z & 0x00FF00) >> 8
         
         return b