001/**
002 * Copyright (c) 2014 Digi International Inc.,
003 * All rights not expressly granted are reserved.
004 *
005 * This Source Code Form is subject to the terms of the Mozilla Public
006 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
007 * You can obtain one at http://mozilla.org/MPL/2.0/.
008 *
009 * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
010 * =======================================================================
011 */
012package com.digi.xbee.api.packet;
013
014/**
015 * This class stores, computes and verifies the checksum of the API packets.
016 * 
017 * <p>To test data integrity, a checksum is calculated and verified on 
018 * non-escaped API data.</p>
019 * 
020 * <p><b>To calculate</b></p>
021 * 
022 * <p>Not including frame delimiters and length, add all bytes keeping only the 
023 * lowest 8 bits of the result and subtract the result from {@code 0xFF}.</p>
024 * 
025 * <p><b>To verify</b></p>
026 * 
027 * <p>Add all bytes (include checksum, but not the delimiter and length). If the 
028 * checksum is correct, the sum will equal {@code 0xFF}.</p>
029 */
030public class XBeeChecksum {
031
032        // Variables.
033        private int value = 0;
034        
035        /**
036         * Adds the given byte to the checksum.
037         * 
038         * @param value Byte to add.
039         */
040        public void add(int value) {
041                this.value += value;
042        }
043        
044        /**
045         * Adds the given data to the checksum.
046         * 
047         * @param data Byte array to add.
048         */
049        public void add(byte[] data) {
050                if (data == null)
051                        return;
052                for (int i = 0; i < data.length; i++)
053                        add(data[i]);
054        }
055        
056        /**
057         * Resets the checksum.
058         */
059        public void reset() {
060                value = 0;
061        }
062        
063        /**
064         * Generates the checksum byte for the API packet.
065         * 
066         * @return Checksum byte.
067         */
068        public int generate() {
069                value = value & 0xFF;
070                return 0xFF - value;
071        }
072        
073        /**
074         * Validates the checksum.
075         * 
076         * @return {@code true} if checksum is valid, {@code false} otherwise.
077         */
078        public boolean validate() {
079                value = value & 0xFF;
080                return value == 0xFF;
081        }
082}