def __init__(self, entity_id, host, token, username, password, country, name, should_poll, image_config, colors, drawables, sizes, texts, attributes, store_map_raw, store_map_image, store_map_path, force_api): super().__init__() self.entity_id = entity_id self.content_type = CONTENT_TYPE self._vacuum = miio.Vacuum(host, token) self._connector = XiaomiCloudConnector(username, password) self._status = CameraStatus.INITIALIZING self._device = None self._name = name self._should_poll = should_poll self._image_config = image_config self._colors = colors self._drawables = drawables self._sizes = sizes self._texts = texts self._attributes = attributes self._store_map_raw = store_map_raw self._store_map_image = store_map_image self._store_map_path = store_map_path self._forced_api = force_api self._used_api = None self._map_saved = None self._image = None self._map_data = None self._logged_in = False self._logged_in_previously = True self._received_map_name_previously = True self._country = country
def cli(ctx, ip: str, token: str, debug: int, id_file: str): """A tool to command Xiaomi Vacuum robot.""" if debug: logging.basicConfig(level=logging.DEBUG) _LOGGER.info("Debug mode active") else: logging.basicConfig(level=logging.INFO) # if we are scanning, we do not try to connect. if ctx.invoked_subcommand == "discover": ctx.obj = "discover" return if ip is None or token is None: click.echo("You have to give ip and token!") sys.exit(-1) start_id = manual_seq = 0 with contextlib.suppress(FileNotFoundError, TypeError, ValueError), open(id_file, "r") as f: x = json.load(f) start_id = x.get("seq", 0) manual_seq = x.get("manual_seq", 0) _LOGGER.debug("Read stored sequence ids: %s", x) vac = miio.Vacuum(ip, token, start_id, debug) vac.manual_seqnum = manual_seq _LOGGER.debug("Connecting to %s with token %s", ip, token) ctx.obj = vac if ctx.invoked_subcommand is None: ctx.invoke(status) cleanup(vac, id_file=id_file)
def cli(ctx, ip: str, token: str, debug: int, id_file: str): """A tool to command Xiaomi Vacuum robot.""" if debug: logging.basicConfig(level=logging.DEBUG) _LOGGER.info("Debug mode active") else: logging.basicConfig(level=logging.INFO) # if we are scanning, we do not try to connect. if ctx.invoked_subcommand == "discover": ctx.obj = "discover" return return if ip is None or token is None: click.echo("You have to give ip and token!") sys.exit(-1) start_id = manual_seq = 0 try: with open(id_file, 'r') as f: x = json.load(f) start_id = x.get("seq", 0) manual_seq = x.get("manual_seq", 0) _LOGGER.debug("Read stored sequence ids: %s" % x) except (FileNotFoundError, TypeError) as ex: _LOGGER.error("Unable to read the stored msgid: %s" % ex) pass vac = miio.Vacuum(ip, token, start_id, debug) vac.manual_seqnum = manual_seq _LOGGER.debug("Connecting to %s with token %s", ip, token) ctx.obj = vac
def miRoboDock(): conf = Config() ip = conf.configOpt["mivac_ip"] token = conf.configOpt["mivac_token"] start_id = 0 vac = miio.Vacuum(ip, token, start_id, True) res = vac.home() jsonresult = {"Response": str(res)} return jsonify(jsonresult)
def main(): logging.basicConfig(level=logging.INFO) ip = os.environ.get('MIROBO_IP') token = os.environ.get('MIROBO_TOKEN') vac = miio.Vacuum(ip, token) info = vac.info() device_identifier = info.mac_address.replace(':', '').lower() TOPICS['firmware_version'] = f'mirobo/status/{device_identifier}/firmware_version' TOPICS['battery'] = f'mirobo/status/{device_identifier}/battery' TOPICS['fanspeed'] = f'mirobo/status/{device_identifier}/fanspeed' TOPICS['is_on'] = f'mirobo/status/{device_identifier}/is_on' TOPICS['sensor_dirt_hours'] = f'mirobo/status/{device_identifier}/sensor_dirt_hours' TOPICS['filter_hours'] = f'mirobo/status/{device_identifier}/filter_hours' TOPICS['main_brush_hours'] = f'mirobo/status/{device_identifier}/main_brush_hours' TOPICS['side_brush_hours'] = f'mirobo/status/{device_identifier}/side_brush_hours' TOPICS['cleaning_summary_count'] = f'mirobo/status/{device_identifier}/cleaning_summary_count' TOPICS['cleaning_summary_total_area'] = f'mirobo/status/{device_identifier}/cleaning_summary_total_area' TOPICS['cleaning_summary_total_hours'] = f'mirobo/status/{device_identifier}/cleaning_summary_total_hours' mqtt.Client.is_connected=False client = mqtt.Client('mirobo') client.on_connect=on_connect client.on_disconnect=on_disconnect client.loop_start() client.connect('mosquitto', 1883, 60) while True: try: # device info publish(client, TOPICS['firmware_version'], info.firmware_version) # status status = vac.status() publish(client, TOPICS['battery'], float(status.battery)) publish(client, TOPICS['fanspeed'], status.fanspeed) publish(client, TOPICS['is_on'], status.is_on) # consumables consumable_status = vac.consumable_status() publish(client, TOPICS['sensor_dirt_hours'], float(consumable_status.sensor_dirty.total_seconds() / 3600)) publish(client, TOPICS['filter_hours'], float(consumable_status.filter.total_seconds() / 3600)) publish(client, TOPICS['main_brush_hours'], float(consumable_status.main_brush.total_seconds() / 3600)) publish(client, TOPICS['side_brush_hours'], float(consumable_status.side_brush.total_seconds() / 3600)) # cleaning stats clean_history = vac.clean_history() publish(client, TOPICS['cleaning_summary_count'], float(clean_history.count)) publish(client, TOPICS['cleaning_summary_total_area'], float(clean_history.total_area)) publish(client, TOPICS['cleaning_summary_total_hours'], float(clean_history.total_duration.total_seconds() / 3600)) except: logging.error("Error getting device status") sleep(5*60)
def __init__(self, hass, host, token, username, password, country, name, image_config, colors, drawables): super().__init__() self.hass = hass self._vacuum = miio.Vacuum(host, token) self._connector = XiaomiCloudConnector(username, password, country) self._name = name self._image_config = image_config self._colors = colors self._drawables = drawables self._image = None self._map_data = None self._logged = False
def _send(self, com, arr, onComplit=None): i = self._showInfo(com + '...') info = None try: r = miio.Vacuum(self.ip, self.tocken) info = r.raw_command(com, arr) self._showInfo(str(info), i) except Exception as e: self._showInfo(str(e), i) finally: onComplit and onComplit(info)
def miRoboStatus(): conf = Config() ip = conf.configOpt["mivac_ip"] token = conf.configOpt["mivac_token"] start_id = 0 vac = miio.Vacuum(ip, token, start_id, True) res = vac.status() jsonresult = { "State": res.state, "Battery": res.battery, "Fanspeed": res.fanspeed, "cleaning_since": str(res.clean_time), "Cleaned_area": res.clean_area } return jsonify(jsonresult)
def _connect(self): if self._connected == False: for i in range(0, self.retry_count_max - self.retry_count): try: self.vakuum = miio.Vacuum(self._ip, self._token, 0, 0) self.retry_count = 1 self._connected = True return True except Exception as e: self.logger.error( "Xiaomi_Robvac: Error {0}, Cycle {1} ".format( e, self.retry_count)) self.retry_count = self.retry_count + 1 self._connected = False return False
def __init__(self, hass, host, token, username, password, country, name, should_poll, image_config, colors, drawables, sizes, texts, attributes): super().__init__() self.hass = hass self._vacuum = miio.Vacuum(host, token) self._connector = XiaomiCloudConnector(username, password, country) self._name = name self._should_poll = should_poll self._image_config = image_config self._colors = colors self._drawables = drawables self._sizes = sizes self._texts = texts self._attributes = attributes self._image = None self._map_data = None self._logged = False
def __init__(self, entity_id, host, token, username, password, country, name, should_poll, image_config, colors, drawables, sizes, texts, attributes): super().__init__() self.entity_id = entity_id self.content_type = CONTENT_TYPE self._vacuum = miio.Vacuum(host, token) self._connector = XiaomiCloudConnector(username, password) self._name = name self._should_poll = should_poll self._image_config = image_config self._colors = colors self._drawables = drawables self._sizes = sizes self._texts = texts self._attributes = attributes self._image = None self._map_data = None self._logged_in = False self._logged_in_previously = True self._received_map_name_previously = True self._country = country
scale = 1 rotate = 0 trim_left = 5 trim_right = 10.5 trim_bottom = 0 trim_top = 15 # ********* CONFIGURATION END ********* processed_colors = {**colors} for room_number, color in room_colors.items(): processed_colors[f"{COLOR_ROOM_PREFIX}{room_number}"] = color map_name = "retry" if not (vacuum_ip == "" or token == ""): vacuum = miio.Vacuum(vacuum_ip, token) counter = 10 while map_name == "retry" and counter > 0: time.sleep(0.1) map_name = vacuum.map()[0] counter = counter - 1 connector = XiaomiCloudConnector(username, password, country) logged = connector.login() if not logged: print("Failed to log in") if map_name != "retry": print("Retrieved map name: " + map_name) raw_map = connector.get_raw_map_data(map_name) raw_file = open("map_data.gz", "wb") raw_file.write(raw_map)
def _send(self, com, arr): try: r = miio.Vacuum(self.ip, self.tocken) self._showInfo(str(r.raw_command(com, arr))) except Exception as e: self._showInfo(str(e))
import miio """ mirobo --ip 192.168.1.6 --token 42783931395962556764314e6e6b4475 start mirobo --ip 192.168.1.6 --token 42783931395962556764314e6e6b4475 zoned-clean [23279,26675,26679,29325,1] docker run --init -d --name="home-assistant" -e "TZ=Asia/Jerusalem" -v C:\workspace\home-assistant\config:/config -p 8123:8123 homeassistant/home-assistant:stable """ IP = "192.168.1.6" TOKEN = "42783931395962556764314e6e6b4475" vac = miio.Vacuum(IP, token=TOKEN, start_id=0, debug=5) print(vac.sound_volume()) #vac.goto(23279, 26675) #vac.home() #vac.find() vac.fresh_map(2)
seen_tokens.append([addr[0], token]) except socket.timeout: print("Discovery done") return seen_tokens except Exception as ex: print("error while reading discover results: %s", ex) break return None if __name__ == '__main__': bots = mirobo_discover() if bots is None or len(bots) == 0: js.close() sys.exit( "No robots found. Please check your wlan is connected to a robot\n" ) bot = miio.Vacuum(ip=bots[0][0], token=bots[0][1], start_id=0, debug=True) print("timezone=", bot.timezone()) print(bot.timer()) # id=1505168889826 # bot.delete_timer(1505168889826) # # cron: # MIN HOUR DAY MON WDAY # 0 8 * * 0,1,2,3,4,5,6 # # fan_speed # bot.add_timer('35 18 * * *', 'start_clean', 99)
import os import miio IP = os.getenv('IP', '') TOKEN = os.getenv('TOKEN', '') whitelist = os.getenv('TRUE_ID', "") robot_cleaner = miio.Vacuum(IP, TOKEN)
def main(): parser = argparse.ArgumentParser( description= 'Flasher for Xiaomi Vacuum.\nFor specific options check \'{} --help\''. format(sys.argv[0])) parser.add_argument('-a', '--address', dest='address', type=str, help='IP address of vacuum cleaner') parser.add_argument('-t', '--token', dest='token', type=str, help='Known token of vacuum') parser.add_argument('-f', '--firmware', dest='firmware', type=str, help='Path to firmware file') parser.add_argument('-i', '--local-ip', dest='local_ip', type=str, help='Override local server IP') args, external = parser.parse_known_args() print('Flasher for Xiaomi Vacuum') ip_address = args.address known_token = args.token firmware = os.path.abspath(args.firmware) if not args.firmware and not os.path.isfile(firmware): print('You should specify firmware file name to install') exit() if not ip_address: print('Address is not set. Trying to discover.') seen_addrs = discover_devices() if len(seen_addrs) == 0: print('No devices discovered.') exit() elif len(seen_addrs) == 1: ip_address = seen_addrs[0] else: ip_address = select_item('Choose device for connection:', seen_addrs) print('Connecting to device {}...'.format(ip_address)) vacuum = miio.Vacuum(ip=ip_address, token=known_token) if not known_token: print('Sending handshake to get token') m = vacuum.do_discover() vacuum.token = m.checksum else: if len(known_token) == 16: known_token = str( binascii.hexlify(bytes(known_token, encoding="utf8"))) try: s = vacuum.status() if s.state == 'Updating': print('Device already updating.') exit() elif s.state != 'Charging': print('Put device to charging station for updating firmware.') exit() except Exception as ex: print('error while checking device:', ex) exit() local_ip = args.local_ip if args.local_ip else findIP(ip_address) os.chdir(os.path.dirname(firmware)) request_handler = http.server.SimpleHTTPRequestHandler httpd = ThreadedHTTPServer(('', 0), request_handler) http_port = httpd.server_address[1] print('Starting local http server...') thread = threading.Thread(target=httpd.handle_request, daemon=True) thread.start() print('Serving http server at {}:{}'.format(local_ip, http_port)) ota_params = { 'mode': 'normal', 'install': '1', 'app_url': 'http://{ip}:{port}/{fw}'.format(ip=local_ip, port=http_port, fw=os.path.basename(firmware)), 'file_md5': md5(firmware), 'proc': 'dnld install' } print('Sending ota command with parameters:', json.dumps(ota_params)) r = vacuum.send('miIO.ota', ota_params) if r[0] == 'ok': print('Ota started!') else: print('Got error response for ota command:', r) exit() ota_progress = 0 while ota_progress < 100: ota_state = vacuum.send('miIO.get_ota_state')[0] ota_progress = vacuum.send('miIO.get_ota_progress')[0] printProgressBar(ota_progress, 100, prefix='Progress:', length=50) sleep(2) print('Firmware downloaded successfully.') httpd.server_close() print('Exiting.') exit()
def __init__(self) -> None: self._vacuum = miio.Vacuum( environ.get('MIROBO_IP', '127.0.0.1'), environ.get('MIROBO_TOKEN'), int(get_value_or_default('vacuum_seq', '0')), )
import miio import math #import sys #sys.path.append("pycharm-debug-py3k.egg") #import pydevd #pydevd.settrace('192.168.1.49', port=12345, stdoutToServer=True, stderrToServer=True) vacuum = miio.Vacuum(ip="192.168.1.51", token="37705464687a564e366a46486f675367") cmd = vacuum.status() cmd2 = vacuum.consumable_status() #cmd3 = vacuum.clean_details(id_=cmd2.ids[0]) print(math.ceil(cmd2.main_brush_left / cmd2.main_brush_total * 100)) print(math.ceil(cmd2.side_brush_left / cmd2.side_brush_total * 100)) print(math.ceil(cmd2.filter_left / cmd2.filter_total * 100)) print(math.ceil(cmd2.sensor_dirty_left / cmd2.sensor_dirty_total * 100)) #print(cmd2) #print(cmd3)