]> git.basschouten.com Git - openhab-addons.git/blob
7d98bc54251dffc8a8111db2ba786a67236bcc7b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.miio.internal.robot;
14
15 import java.io.ByteArrayOutputStream;
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.PrintWriter;
21 import java.io.StringWriter;
22 import java.security.MessageDigest;
23 import java.security.NoSuchAlgorithmException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.zip.GZIPInputStream;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.miio.internal.Utils;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link RRMapFileParser} is used to parse the RR map file format created by Xiaomi / RockRobo vacuum
39  *
40  * @author Marcel Verpaalen - Initial contribution
41  */
42 @NonNullByDefault
43 public class RRMapFileParser {
44     public static final int CHARGER = 1;
45     public static final int IMAGE = 2;
46     public static final int PATH = 3;
47     public static final int GOTO_PATH = 4;
48     public static final int GOTO_PREDICTED_PATH = 5;
49     public static final int CURRENTLY_CLEANED_ZONES = 6;
50     public static final int GOTO_TARGET = 7;
51     public static final int ROBOT_POSITION = 8;
52     public static final int NO_GO_AREAS = 9;
53     public static final int VIRTUAL_WALLS = 10;
54     public static final int BLOCKS = 11;
55     public static final int MOB_FORBIDDEN_AREA = 12;
56     public static final int OBSTACLES = 13;
57     public static final int IGNORED_OBSTACLES = 14;
58     public static final int OBSTACLES2 = 15;
59     public static final int IGNORED_OBSTACLES2 = 16;
60     public static final int CARPET_MAP = 17;
61     public static final int MOP_PATH = 18;
62     public static final int CARPET_FORBIDDEN_AREA = 19;
63     public static final int SMART_ZONES_PATH_TYPE = 20;
64     public static final int SMART_ZONES = 21;
65     public static final int CUSTOM_CARPET = 22;
66     public static final int CL_FORBIDDEN_ZONES = 23;
67     public static final int FLOOR_MAP = 24;
68     public static final int FURNITURES = 25;
69     public static final int DOCK_TYPE = 26;
70     public static final int ENEMIES = 27;
71     public static final int DIGEST = 1024;
72     public static final int HEADER = 0x7272;
73
74     public static final String PATH_POINT_LENGTH = "pointLength";
75     public static final String PATH_POINT_SIZE = "pointSize";
76     public static final String PATH_ANGLE = "angle";
77
78     private byte[] image = new byte[] { 0 };
79     private final int majorVersion;
80     private final int minorVersion;
81     private final int mapIndex;
82     private final int mapSequence;
83     private boolean isValid;
84
85     private int imgHeight;
86     private int imgWidth;
87     private int imageSize;
88     private int top;
89     private int left;
90
91     private int chargerX;
92     private int chargerY;
93     private int roboX;
94     private int roboY;
95     private int roboA;
96     private float gotoX = 0;
97     private float gotoY = 0;
98     private Map<Integer, ArrayList<float[]>> paths = new HashMap<>();
99     private Map<Integer, Map<String, Integer>> pathsDetails = new HashMap<>();
100     private Map<Integer, ArrayList<float[]>> areas = new HashMap<>();
101     private ArrayList<float[]> walls = new ArrayList<>();
102     private ArrayList<float[]> zones = new ArrayList<>();
103     private Map<Integer, ArrayList<int[]>> obstacles = new HashMap<>();
104     private byte[] blocks = new byte[0];
105     private int[] carpetMap = {};
106     private int[] mopPath = {};
107
108     private final Logger logger = LoggerFactory.getLogger(RRMapFileParser.class);
109
110     public RRMapFileParser(byte[] raw) {
111         boolean printBlockDetails = false;
112         int mapHeaderLength = getUInt16(raw, 0x02);
113         int mapDataLength = getUInt32LE(raw, 0x04);
114         this.majorVersion = getUInt16(raw, 0x08);
115         this.minorVersion = getUInt16(raw, 0x0A);
116         this.mapIndex = getUInt32LE(raw, 0x0C);
117         this.mapSequence = getUInt32LE(raw, 0x10);
118
119         int blockStartPos = getUInt16(raw, 0x02); // main header length
120         while (blockStartPos < raw.length) {
121             int blockHeaderLength = getUInt16(raw, blockStartPos + 0x02);
122             byte[] header = getBytes(raw, blockStartPos, blockHeaderLength);
123             int blocktype = getUInt16(header, 0x00);
124             int blockDataLength = getUInt32LE(header, 0x04);
125             int blockDataStart = blockStartPos + blockHeaderLength;
126             byte[] data = getBytes(raw, blockDataStart, blockDataLength);
127
128             switch (blocktype) {
129                 case CHARGER:
130                     this.chargerX = getUInt32LE(raw, blockStartPos + 0x08);
131                     this.chargerY = getUInt32LE(raw, blockStartPos + 0x0C);
132                     break;
133                 case IMAGE:
134                     this.imageSize = blockDataLength;// (getUInt32LE(raw, blockStartPos + 0x04));
135                     if (blockHeaderLength > 0x1C) {
136                         logger.debug("block 2 unknown value @pos 8: {}", getUInt32LE(header, 0x08));
137                     }
138                     this.top = getUInt32LE(header, blockHeaderLength - 16);
139                     this.left = getUInt32LE(header, blockHeaderLength - 12);
140                     this.imgHeight = (getUInt32LE(header, blockHeaderLength - 8));
141                     this.imgWidth = getUInt32LE(header, blockHeaderLength - 4);
142                     this.image = data;
143                     break;
144                 case ROBOT_POSITION:
145                     this.roboX = getUInt32LE(data, 0x00);
146                     this.roboY = getUInt32LE(data, 0x04);
147                     if (blockDataLength > 8) { // model S6
148                         this.roboA = getUInt32LE(data, 0x08);
149                     }
150                     break;
151                 case PATH:
152                 case GOTO_PATH:
153                 case GOTO_PREDICTED_PATH:
154                     ArrayList<float[]> path = new ArrayList<float[]>();
155                     Map<String, Integer> detail = new HashMap<String, Integer>();
156                     int pairs = getUInt32LE(header, 0x04) / 4;
157                     detail.put(PATH_POINT_LENGTH, getUInt32LE(header, 0x08));
158                     detail.put(PATH_POINT_SIZE, getUInt32LE(header, 0x0C));
159                     detail.put(PATH_ANGLE, getUInt32LE(header, 0x10));
160                     for (int pathpair = 0; pathpair < pairs; pathpair++) {
161                         float x = (getUInt16(getBytes(raw, blockDataStart + pathpair * 4, 2)));
162                         float y = getUInt16(getBytes(raw, blockDataStart + pathpair * 4 + 2, 2));
163                         path.add(new float[] { x, y });
164                     }
165                     paths.put(blocktype, path);
166                     pathsDetails.put(blocktype, detail);
167                     break;
168                 case CURRENTLY_CLEANED_ZONES:
169                     int zonePairs = getUInt16(header, 0x08);
170                     for (int zonePair = 0; zonePair < zonePairs; zonePair++) {
171                         float x0 = (getUInt16(raw, blockDataStart + zonePair * 8));
172                         float y0 = getUInt16(raw, blockDataStart + zonePair * 8 + 2);
173                         float x1 = (getUInt16(raw, blockDataStart + zonePair * 8 + 4));
174                         float y1 = getUInt16(raw, blockDataStart + zonePair * 8 + 6);
175                         zones.add(new float[] { x0, y0, x1, y1 });
176                     }
177                     break;
178                 case GOTO_TARGET:
179                     this.gotoX = getUInt16(data, 0x00);
180                     this.gotoY = getUInt16(data, 0x02);
181                     break;
182                 case DIGEST:
183                     isValid = Arrays.equals(data, sha1Hash(getBytes(raw, 0, mapHeaderLength + mapDataLength - 20)));
184                     break;
185                 case VIRTUAL_WALLS:
186                     int wallPairs = getUInt16(header, 0x08);
187                     for (int wallPair = 0; wallPair < wallPairs; wallPair++) {
188                         float x0 = (getUInt16(raw, blockDataStart + wallPair * 8));
189                         float y0 = getUInt16(raw, blockDataStart + wallPair * 8 + 2);
190                         float x1 = (getUInt16(raw, blockDataStart + wallPair * 8 + 4));
191                         float y1 = getUInt16(raw, blockDataStart + wallPair * 8 + 6);
192                         walls.add(new float[] { x0, y0, x1, y1 });
193                     }
194                     break;
195                 case NO_GO_AREAS:
196                 case MOB_FORBIDDEN_AREA:
197                 case CARPET_FORBIDDEN_AREA:
198                     int areaPairs = getUInt16(header, 0x08);
199                     ArrayList<float[]> area = new ArrayList<float[]>();
200                     for (int areaPair = 0; areaPair < areaPairs; areaPair++) {
201                         float x0 = (getUInt16(raw, blockDataStart + areaPair * 16));
202                         float y0 = getUInt16(raw, blockDataStart + areaPair * 16 + 2);
203                         float x1 = (getUInt16(raw, blockDataStart + areaPair * 16 + 4));
204                         float y1 = getUInt16(raw, blockDataStart + areaPair * 16 + 6);
205                         float x2 = (getUInt16(raw, blockDataStart + areaPair * 16 + 8));
206                         float y2 = getUInt16(raw, blockDataStart + areaPair * 16 + 10);
207                         float x3 = (getUInt16(raw, blockDataStart + areaPair * 16 + 12));
208                         float y3 = getUInt16(raw, blockDataStart + areaPair * 16 + 14);
209                         area.add(new float[] { x0, y0, x1, y1, x2, y2, x3, y3 });
210                     }
211                     areas.put(Integer.valueOf(blocktype & 0xFF), area);
212                     break;
213                 case OBSTACLES:
214                 case IGNORED_OBSTACLES:
215                     int obstaclePairs = getUInt16(header, 0x08);
216                     ArrayList<int[]> obstacle = new ArrayList<>();
217                     for (int obstaclePair = 0; obstaclePair < obstaclePairs; obstaclePair++) {
218                         int x0 = getUInt16(data, obstaclePair * 5 + 0);
219                         int y0 = getUInt16(data, obstaclePair * 5 + 2);
220                         int u = data[obstaclePair * 5 + 0] & 0xFF;
221                         obstacle.add(new int[] { x0, y0, u });
222                     }
223                     obstacles.put(Integer.valueOf(blocktype & 0xFF), obstacle);
224                     break;
225                 case OBSTACLES2:
226                     int obstacle2Pairs = getUInt16(header, 0x08);
227                     if (obstacle2Pairs == 0) {
228                         break;
229                     }
230                     int obstacleDataLenght = blockDataLength / obstacle2Pairs;
231                     logger.trace("block 15 records lenght: {}", obstacleDataLenght);
232                     ArrayList<int[]> obstacle2 = new ArrayList<>();
233                     for (int obstaclePair = 0; obstaclePair < obstacle2Pairs; obstaclePair++) {
234                         int x0 = getUInt16(data, obstaclePair * obstacleDataLenght + 0);
235                         int y0 = getUInt16(data, obstaclePair * obstacleDataLenght + 2);
236                         int u0 = getUInt16(data, obstaclePair * obstacleDataLenght + 4);
237                         int u1 = getUInt16(data, obstaclePair * obstacleDataLenght + 6);
238                         int u2 = getUInt32LE(data, obstaclePair * obstacleDataLenght + 8);
239                         if (obstacleDataLenght == 28) {
240                             if ((data[obstaclePair * obstacleDataLenght + 12] & 0xFF) == 0) {
241                                 logger.trace("obstacle with photo: No text");
242                             } else {
243                                 byte[] txt = getBytes(data, obstaclePair * obstacleDataLenght + 12, 16);
244                                 logger.trace("obstacle with photo: {}", new String(txt));
245                             }
246                             obstacle2.add(new int[] { x0, y0, u0, u1, u2 });
247                         } else {
248                             int u3 = getUInt32LE(data, obstaclePair * obstacleDataLenght + 12);
249                             obstacle2.add(new int[] { x0, y0, u0, u1, u2, u3 });
250                             logger.trace("obstacle without photo.");
251                         }
252                     }
253                     obstacles.put(Integer.valueOf(blocktype & 0xFF), obstacle2);
254                     break;
255                 case IGNORED_OBSTACLES2:
256                     int ignoredObstaclePairs = getUInt16(header, 0x08);
257                     ArrayList<int[]> ignoredObstacle = new ArrayList<>();
258                     for (int obstaclePair = 0; obstaclePair < ignoredObstaclePairs; obstaclePair++) {
259                         int x0 = getUInt16(data, obstaclePair * 6 + 0);
260                         int y0 = getUInt16(data, obstaclePair * 6 + 2);
261                         int u = getUInt16(data, obstaclePair * 6 + 4);
262                         ignoredObstacle.add(new int[] { x0, y0, u });
263                     }
264                     obstacles.put(Integer.valueOf(blocktype & 0xFF), ignoredObstacle);
265                     break;
266                 case CARPET_MAP:
267                     carpetMap = new int[blockDataLength];
268                     for (int carpetNode = 0; carpetNode < blockDataLength; carpetNode++) {
269                         carpetMap[carpetNode] = data[carpetNode] & 0xFF;
270                     }
271                     break;
272                 case MOP_PATH:
273                     mopPath = new int[blockDataLength];
274                     for (int mopNode = 0; mopNode < blockDataLength; mopNode++) {
275                         mopPath[mopNode] = data[mopNode] & 0xFF;
276                     }
277                     break;
278                 case BLOCKS:
279                     int blocksPairs = getUInt16(header, 0x08);
280                     blocks = getBytes(data, 0, blocksPairs);
281                     break;
282                 case SMART_ZONES_PATH_TYPE:
283                 case SMART_ZONES:
284                 case CUSTOM_CARPET:
285                 case CL_FORBIDDEN_ZONES:
286                 case FLOOR_MAP:
287                 case FURNITURES:
288                 case DOCK_TYPE:
289                 case ENEMIES:
290                     // new blocktypes not yet decoded
291                     break;
292                 default:
293                     logger.info("Unknown blocktype {} (pls report to author)", blocktype);
294                     printBlockDetails = true;
295             }
296             if (logger.isTraceEnabled() || printBlockDetails) {
297                 logger.debug("Blocktype: {}", Integer.toString(blocktype));
298                 logger.debug("Header len: {}   data len: {} ", Integer.toString(blockHeaderLength),
299                         Integer.toString(blockDataLength));
300                 logger.debug("H: {}", Utils.getSpacedHex(header));
301                 if (blockDataLength > 0) {
302                     logger.debug("D: {}", (blockDataLength < 60 ? Utils.getSpacedHex(data)
303                             : Utils.getSpacedHex(getBytes(data, 0, 60))));
304                 }
305                 printBlockDetails = false;
306             }
307             blockStartPos = blockStartPos + blockDataLength + (header[2] & 0xFF);
308         }
309     }
310
311     public static byte[] readRRMapFile(File file) throws IOException {
312         return readRRMapFile(new FileInputStream(file));
313     }
314
315     public static byte[] readRRMapFile(InputStream is) throws IOException {
316         ByteArrayOutputStream baos = new ByteArrayOutputStream();
317         try (GZIPInputStream in = new GZIPInputStream(is)) {
318             int bufsize = 1024;
319             byte[] buf = new byte[bufsize];
320             int readbytes = 0;
321             readbytes = in.read(buf);
322             while (readbytes != -1) {
323                 baos.write(buf, 0, readbytes);
324                 readbytes = in.read(buf);
325             }
326             baos.flush();
327             return baos.toByteArray();
328         }
329     }
330
331     private byte[] getBytes(byte[] raw, int pos, int len) {
332         return java.util.Arrays.copyOfRange(raw, pos, pos + len);
333     }
334
335     private int getUInt32LE(byte[] bytes, int pos) {
336         int value = bytes[0 + pos] & 0xFF;
337         value |= (bytes[1 + pos] << 8) & 0xFFFF;
338         value |= (bytes[2 + pos] << 16) & 0xFFFFFF;
339         value |= (bytes[3 + pos] << 24) & 0xFFFFFFFF;
340         return value;
341     }
342
343     private int getUInt16(byte[] bytes) {
344         return getUInt16(bytes, 0);
345     }
346
347     private int getUInt16(byte[] bytes, int pos) {
348         int value = bytes[0 + pos] & 0xFF;
349         value |= (bytes[1 + pos] << 8) & 0xFFFF;
350         return value;
351     }
352
353     @Override
354     public String toString() {
355         StringWriter sw = new StringWriter();
356         PrintWriter pw = new PrintWriter(sw);
357         pw.printf("RR Map:\tMajor Version: %d Minor version: %d Map Index: %d Map Sequence: %d\r\n", majorVersion,
358                 minorVersion, mapIndex, mapSequence);
359         pw.printf("Image:\tsize: %9d\ttop: %9d\tleft: %9d height: %9d width: %9d\r\n", imageSize, top, left, imgHeight,
360                 imgWidth);
361         pw.printf("Charger pos:\tX: %.0f\tY: %.0f\r\n", getChargerX(), getChargerY());
362         pw.printf("Robo pos:\tX: %.0f\tY: %.0f\tAngle: %d\r\n", getRoboX(), getRoboY(), getRoboA());
363         pw.printf("Goto:\tX: %.0f\tY: %.0f\r\n", getGotoX(), getGotoY());
364         for (Entry<Integer, ArrayList<float[]>> area : areas.entrySet()) {
365             switch (area.getKey()) {
366                 case NO_GO_AREAS:
367                     pw.print("Regular No Go zones:\t");
368                     break;
369                 case MOB_FORBIDDEN_AREA:
370                     pw.print("Mop No Go zones:\t");
371                     break;
372                 case CARPET_FORBIDDEN_AREA:
373                     pw.print("Carpet No Go zones:\t");
374                     break;
375                 default:
376                     pw.print("Unknown type zones:\t");
377             }
378             pw.printf("%d\r\n", area.getValue().size());
379             printAreaDetails(area.getValue(), pw);
380         }
381         pw.printf("Walls:\t%d\r\n", walls.size());
382         printAreaDetails(walls, pw);
383         pw.printf("Zones:\t%d\r\n", zones.size());
384         printAreaDetails(zones, pw);
385         for (Entry<Integer, ArrayList<int[]>> obstacleType : obstacles.entrySet()) {
386             pw.printf("Obstacles Type (%d):\t%d\r\n", obstacleType.getKey(), obstacleType.getValue().size());
387             printObstacleDetails(obstacleType.getValue(), pw);
388         }
389         pw.printf("Blocks:\t%d\r\n", blocks.length);
390         pw.print("Paths:");
391         for (Entry<Integer, Map<String, Integer>> pathDetail : pathsDetails.entrySet()) {
392             pw.printf("\r\nPath type:\t%d", pathDetail.getKey());
393             for (String detail : pathDetail.getValue().keySet()) {
394                 pw.printf("   %s: %d", detail, pathDetail.getValue().get(detail));
395             }
396         }
397         pw.println();
398         pw.printf("Carpet Map:\t%d\r\n", carpetMap.length);
399         pw.printf("Mop Path:\t%d\r\n", mopPath.length);
400         pw.close();
401         return sw.toString();
402     }
403
404     private void printAreaDetails(@Nullable ArrayList<float[]> areas, PrintWriter pw) {
405         if (areas == null) {
406             pw.println("null");
407             return;
408         }
409         areas.forEach(area -> {
410             pw.print("\tArea coordinates:");
411             for (int i = 0; i < area.length; i++) {
412                 pw.printf("\t%.0f", area[i]);
413             }
414             pw.println();
415         });
416     }
417
418     private void printObstacleDetails(@Nullable ArrayList<int[]> obstacle, PrintWriter pw) {
419         if (obstacle == null) {
420             pw.println("null");
421             return;
422         }
423         obstacle.forEach(area -> {
424             pw.print("\tObstacle coordinates:");
425             for (int i = 0; i < area.length; i++) {
426                 pw.printf("\t%d", area[i]);
427             }
428             pw.println();
429         });
430     }
431
432     /**
433      * Compute SHA-1 hash value for the byte array
434      *
435      * @param inBytes ByteArray to be hashed
436      * @return hash value
437      */
438     public static byte[] sha1Hash(byte[] inBytes) {
439         try {
440             MessageDigest md = MessageDigest.getInstance("SHA-1");
441             return md.digest(inBytes);
442         } catch (NoSuchAlgorithmException e) {
443             return new byte[] { 0x00 };
444         }
445     }
446
447     public int getMajorVersion() {
448         return majorVersion;
449     }
450
451     public int getMinorVersion() {
452         return minorVersion;
453     }
454
455     public int getMapIndex() {
456         return mapIndex;
457     }
458
459     public int getMapSequence() {
460         return mapSequence;
461     }
462
463     public boolean isValid() {
464         return isValid;
465     }
466
467     public byte[] getImage() {
468         return image;
469     }
470
471     public int getImageSize() {
472         return imageSize;
473     }
474
475     public int getImgHeight() {
476         return imgHeight;
477     }
478
479     public int getImgWidth() {
480         return imgWidth;
481     }
482
483     public int getTop() {
484         return top;
485     }
486
487     public int getLeft() {
488         return left;
489     }
490
491     public ArrayList<float[]> getZones() {
492         return zones;
493     }
494
495     public float getRoboX() {
496         return roboX;
497     }
498
499     public float getRoboY() {
500         return roboY;
501     }
502
503     public float getChargerX() {
504         return chargerX;
505     }
506
507     public float getChargerY() {
508         return chargerY;
509     }
510
511     public float getGotoX() {
512         return gotoX;
513     }
514
515     public float getGotoY() {
516         return gotoY;
517     }
518
519     public int getRoboA() {
520         return roboA;
521     }
522
523     public Map<Integer, ArrayList<float[]>> getPaths() {
524         return paths;
525     }
526
527     public Map<Integer, Map<String, Integer>> getPathsDetails() {
528         return pathsDetails;
529     }
530
531     public ArrayList<float[]> getWalls() {
532         return walls;
533     }
534
535     public Map<Integer, ArrayList<float[]>> getAreas() {
536         return areas;
537     }
538
539     public Map<Integer, ArrayList<int[]>> getObstacles() {
540         return obstacles;
541     }
542
543     public byte[] getBlocks() {
544         return blocks;
545     }
546
547     public final int[] getCarpetMap() {
548         return carpetMap;
549     }
550
551     public final int[] getMopPath() {
552         return mopPath;
553     }
554 }