001/**
002 * Copyright 2017, Digi International Inc.
003 *
004 * This Source Code Form is subject to the terms of the Mozilla Public
005 * License, v. 2.0. If a copy of the MPL was not distributed with this
006 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
007 *
008 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 
009 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 
010 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 
011 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 
012 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 
013 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 
014 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
015 */
016package com.digi.xbee.api.packet;
017
018/**
019 * This class stores, computes and verifies the checksum of the API packets.
020 * 
021 * <p>To test data integrity, a checksum is calculated and verified on 
022 * non-escaped API data.</p>
023 * 
024 * <p><b>To calculate</b></p>
025 * 
026 * <p>Not including frame delimiters and length, add all bytes keeping only the 
027 * lowest 8 bits of the result and subtract the result from {@code 0xFF}.</p>
028 * 
029 * <p><b>To verify</b></p>
030 * 
031 * <p>Add all bytes (include checksum, but not the delimiter and length). If the 
032 * checksum is correct, the sum will equal {@code 0xFF}.</p>
033 */
034public class XBeeChecksum {
035
036        // Variables.
037        private int value = 0;
038        
039        /**
040         * Adds the given byte to the checksum.
041         * 
042         * @param value Byte to add.
043         */
044        public void add(int value) {
045                this.value += value;
046        }
047        
048        /**
049         * Adds the given data to the checksum.
050         * 
051         * @param data Byte array to add.
052         */
053        public void add(byte[] data) {
054                if (data == null)
055                        return;
056                for (int i = 0; i < data.length; i++)
057                        add(data[i]);
058        }
059        
060        /**
061         * Resets the checksum.
062         */
063        public void reset() {
064                value = 0;
065        }
066        
067        /**
068         * Generates the checksum byte for the API packet.
069         * 
070         * @return Checksum byte.
071         */
072        public int generate() {
073                value = value & 0xFF;
074                return 0xFF - value;
075        }
076        
077        /**
078         * Validates the checksum.
079         * 
080         * @return {@code true} if checksum is valid, {@code false} otherwise.
081         */
082        public boolean validate() {
083                value = value & 0xFF;
084                return value == 0xFF;
085        }
086}