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