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