def connect(self):
     try:
         if self.blestatus.isscaninprogress():
             self.blestatus.requeststopscan(self.taskindex)
             return False
     except Exception as e:
         return False
     cstart = time.time()
     while self.blestatus.norequesters(
     ) == False or self.blestatus.nodataflows() == False:
         time.sleep(0.5)
         misc.addLog(
             rpieGlobals.LOG_LEVEL_DEBUG_MORE,
             "BLE line not free for P513! " + str(self.blestatus.dataflow))
         try:
             if time.time() - cstart > int(self.taskdevicepluginconfig[3]):
                 self.blestatus.dataflow = []  #reset line by force
         except:
             pass
     self.blestatus.registerdataprogress(self.taskindex)
     try:
         self.BLEPeripheral = Lywsd02Client(
             str(self.taskdevicepluginconfig[0]), int(self.interval))
         self.connected = True
         misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                     "BLE connected " + str(self.taskdevicepluginconfig[0]))
         time.sleep(1)
     except Exception as e:
         self.connected = False
         self.initialized = False
         self.blestatus.unregisterdataprogress(self.taskindex)
         misc.addLog(
             rpieGlobals.LOG_LEVEL_ERROR,
             "BLE connection failed " + str(self.taskdevicepluginconfig[0]))
Beispiel #2
0
def readVal():
    #print("Polling...")
    for device in devices :
        try:
            print("Polling from "+device["mac"]+" of type "+device["type"])
            """Poll data from the sensor."""
            if (device["type"] == "MJ_HT_V1") :
                poller = MiTempBtPoller(device["mac"], GatttoolBackend, retries=1)
                #print("Getting data from Mi Temperature and Humidity Sensor")
                #print("FW: {}".format(poller.firmware_version()))
                #print("Name: {}".format(poller.name()))
                print("Battery: {}".format(poller.parameter_value(MI_BATTERY)))
                temperature = float(poller.parameter_value(MI_TEMPERATURE))
                print("Temperature: "+str(temperature))
                blynk.virtual_write(device["temperature"], temperature)
                humidity = float(poller.parameter_value(MI_HUMIDITY))
                print("Humidity: "+str(humidity))
                blynk.virtual_write(device["humidity"], humidity)
            if (device["type"] == "LYWSD02") :
                client = Lywsd02Client(device["mac"])
                print("Battery: {}".format(client.battery))
                temperature = float(client.temperature)
                print("Temperature: "+str(temperature))
                blynk.virtual_write(device["temperature"], temperature)
                humidity = float(client.humidity)
                print("Humidity: "+str(humidity))
                blynk.virtual_write(device["humidity"], humidity)
        except Exception as e:
            print (e)
Beispiel #3
0
def main():
    setup_logging()
    device_mac = sys.argv[1]

    with Lywsd02Client(device_mac).connect() as client:
        logging.info('sync time')
        client.time = datetime.now()

        logging.info('check sync result')
        print(client.time)
  def _setup(self):
    from lywsd02 import Lywsd02Client

    self._devices = {}

    _LOGGER.info("Adding %d %s devices", len(self.devices), repr(self))
    for device in self.devices:
      name = device.get('name')
      mac = device.get('mac')
      domoticz_idx = device.get('domoticz_idx')
      _LOGGER.debug("Adding %s device '%s' (%s)", repr(self), name, mac)
      self._devices[name] = {"mac": mac, "client": Lywsd02Client(mac), "domoticz_idx": domoticz_idx}
Beispiel #5
0
 def connect(self):
     try:
         self.BLEPeripheral = Lywsd02Client(
             str(self.taskdevicepluginconfig[0]),
             data_request_timeout=int(self.interval))
         self.connected = True
         misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                     "BLE connected " + str(self.taskdevicepluginconfig[0]))
         time.sleep(1)
     except:
         self.connected = False
         self.initialized = False
         misc.addLog(
             rpieGlobals.LOG_LEVEL_ERROR,
             "BLE connection failed " + str(self.taskdevicepluginconfig[0]))
Beispiel #6
0
def gather_readings(devices, max_attempts):
    """
    Connects to each device and gathers the readings
    """
    keys = devices.keys()

    for addr in keys:
        device = devices[addr]
        attempts = 0
        readings_complete = False
        while attempts < max_attempts and not readings_complete:
            try:
                attempts += 1
                print(
                    f"Attempting to read from sensor {device['sensor_name']}..."
                )
                client = Lywsd02Client(device['addr'])
                reading = {
                    'timestamp': datetime.now().isoformat(),
                    'temperature': client.temperature,
                    'humidity': client.humidity,
                    'battery': client.battery
                }
                devices[addr]['last reading'] = reading
                update_histories(devices[addr], reading)
                print(
                    f"Device {device['sensor_name']} ({device['addr']}) -> {dumps(reading, sort_keys=True, indent=4)}"
                )
                readings_complete = True
            except KeyboardInterrupt:
                print("User cancelled scan.")
                readings_complete = True

            except TimeoutError:
                print(f"Data wasn't sent ({attempts}/{max_attempts})")

            except BTLEDisconnectError:
                print(
                    f"Failed to connect. Perhaps the device is busy elsewhere."
                )
                # Force an early end to the loop - Waiting for a connection is time consuming
                attempts = max_attempts

            except Exception as e:
                # print(e)
                # print(f"Failed to gather readings for {device['addr']}. Trying again...")
                raise e
    return devices
Beispiel #7
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.timer1s = False
     self.readinprogress = 0
     #  self.connected = False
     #  self.uservar[0] = 0
     #  self.uservar[1] = 0
     if self.enabled:
         try:
             self.BLEPeripheral = Lywsd02Client(
                 str(self.taskdevicepluginconfig[0]),
                 data_request_timeout=int(self.interval))
             self.initialized = True
             self.connected = True
             time.sleep(1)
         except:
             self.initialized = False
 def connect(self):
     try:
         if self.blestatus.isscaninprogress():
             self.blestatus.requeststopscan(self.taskindex)
             return False
     except Exception as e:
         return False
     self.blestatus.registerdataprogress(self.taskindex)
     try:
         self.BLEPeripheral = Lywsd02Client(
             str(self.taskdevicepluginconfig[0]), int(self.interval))
         self.connected = True
         misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                     "BLE connected " + str(self.taskdevicepluginconfig[0]))
         time.sleep(1)
     except Exception as e:
         self.connected = False
         self.initialized = False
         self.blestatus.unregisterdataprogress(self.taskindex)
         misc.addLog(
             rpieGlobals.LOG_LEVEL_ERROR,
             "BLE connection failed " + str(self.taskdevicepluginconfig[0]))
Beispiel #9
0
import datetime

from lywsd02 import Lywsd02Client

mac = '3F:59:C8:80:70:BE'

client = Lywsd02Client(mac)

if __name__ == '__main__':
    dt = datetime.datetime.now()
    with client.connect():
        temperature = client.temperature
        humidity = client.humidity
        time = client.time[0]
        battery = client.battery
    print(battery)
def error(*message):
    """
    """
    RED = '\033[95m'
    NORMAL = '\u001b[0m'
    print(RED, *message, NORMAL, file=stderr)

if __name__ == '__main__':

    if len(argv) < 2:
        error("Address of the Xiaomi sensor device is required")
        exit(1)

    try:
        error(f"Attempting to connect to {argv[1]}")
        client = Lywsd02Client(argv[1])
        reading = {
            'timestamp': datetime.now().isoformat(),
            'temperature': client.temperature,
            'humidity': client.humidity,
            'battery': client.battery
        }
        print(dumps(reading, indent=2))
        error(dumps(reading, indent=2))
        exit(ExitCodes.OK)

    except KeyboardInterrupt:
        error("User cancelled scan.")
        exit(ExitCodes.USER_CANCELLED)

    except TimeoutError:
Beispiel #11
0
def create_client():
    return Lywsd02Client(mac)