Blockchain IoT for Smart Electric Vehicles Battery Management

: Electric Vehicles (EVs) have generated a lot of interest in recent years, due to the advances in battery life and low pollution. Similarly, the expansion of the Internet of Things (IoT) allowed more and more devices to be interconnected. One major problem EVs face today is the limited range of the battery and the limited number of charging or battery swapping stations. A solution is to not only build the necessary infrastructure, but also to be able to correctly estimate the remaining power using an efﬁcient battery management system (BMS). For some EVs, battery swapping can also be an option, either at registered stations, or even directly from other EV drivers. Thus, a network of EV information is required, so that a successful battery charge or swap can be made available for drivers. In this paper two blockchain implementations for an EV BMS are presented, using blockchain as the network and data layer of the application. The ﬁrst implementation uses Ethereum as the blockchain framework for developing smart contracts, while the second uses a directed acyclic graph (DAG), on top of the IOTA tangle. The two approaches are implemented and compared, demonstrating that both platforms can provide a viable solution for an efﬁcient, semi-decentralized, data-driven BMS.


Introduction
In recent years the development of electric vehicles has become one of the main interests for most major automobile manufacturers. One of the most concerning aspects for consumers regarding the adoption of electrical vehicles (EVs) is the autonomy and the lack of infrastructure in most areas, except for large cities.
The history of electric vehicles dates back almost to the introduction of the electric motor. EVs can be classified in the following categories: hybrid electric vehicles (HEVs), plug-in hybrid electric vehicles (PHEVs), and battery electric vehicles (BEVs) [1]. HEVs and PHEVs are powered by two sources: an electric motor and an internal combustion engine which can operate independently or in parallel, while BEVs operate solely using an electric motor powered by batteries or fuel-cells (FCEV) [2]. Moreover, HEVs do not provide an external charger for the batteries, while PHEVs allow external battery charging.
For HEVs and PHEVs, multiple drive-train configurations are available. Series operation EVs use only the electric motor for propulsion, which is coupled with the transmission, while the internal combustion engine is used solely to charge the battery when the state of charge is low. This method is useful for city driving, where frequent start-stops are required. The parallel operation uses both engines for propulsion, by simultaneously transmitting power to the wheels, thus improving the securing IoT applications [16]. Odysseas and Gialelis introduced a IOTA-based sensor node system [17], while Bartolomeu et al. used IOTA for vehicular applications [18]. This paper presents a blockchain application for electric vehicles' (EVs) battery charge and swap, considering two approaches: custom Ethereum blockchain and the IOTA public tangle. For both scenarios, the performance of the system is analyzed, highlighting the advantages and disadvantages of each method. The application is tested using lithium-polymer (LiPo) batteries driving DC motors in an environment similar to that of an EV. The battery voltage and state of charge (SOC) is continuously monitored and the data are stored on the blockchain, together with the required functionalities, such as user and battery information and charge/swap requests.
In the following sections, the paper will present the general background knowledge for blockchain, smart contracts and the IOTA tangle (Section 2), electric vehicles batteries and SOC estimation (Section 3), the proposed application structure and test build (Section 4), followed by the results and comparison between the two proposed methods (Section 5), the general discussion and the conclusions (Sections 6 and 7).

Blockchain and Distributed Ledgers
Since the introduction of blockchain in 2008, blockchain and cryptocurrencies have become mainstream terms. The technology proposes a network similar to that of a distributed ledger technology(DLT). Specifically, it implements a peer-to-peer (P2P) network of distributed data sets shared over multiple locations, where every change in the ledger is reflected in all copies on the network [19]. This means that once a change is submitted by one of the participants, it must be validated and approved by the entire network before it is added to the ledger. To achieve this, a consensus mechanism is required, so that the information, once accepted, cannot be altered by any user or group of users. Different implementations of the blockchain technology provide different methods of consensus, but in most cases consensus is achieved by means of cryptographic functions.
The first blockchain application was introduced in [10], where the cryptocurrency Bitcoin was introduced, with the goal to replace the trust provided by a 3rd party with proof. The term blockchain suggests that the network consists of a series (or chain) of blocks, linked together by means of a cryptographic hash function ( Figure 1). Each block can have multiple transactions (Tx1, Tx2, . . . ). When a new block is created, the corresponding transactions are stored as a Merkle tree (or hash tree), where each leaf (data) node is labeled with its cryptographic hash and each non-leaf node is labeled with the hash of the labels of its children [20]. When the block is created, only the root node of the hash tree is included in the block, which allows for old blocks to be compacted. Each new block includes the reference to the previous block hash. The network participants (or miners) will generate the corresponding hash of the new block with the restrictions imposed by the consensus algorithm (difficulty of the hash function). The miners can inject a nonce in order to find a resulting hash that respects the network specifications. Once this hash is created, the new block is added to the chain and the other users must validate and approve the block by verifying the generated hash. Once the block has been confirmed by the network it can no longer be changed, as any change on the block (or any of the previous blocks) will invalidate the computed hash and will be rejected by the network. In this way, data immutability is achieved, which is one of the main advantages of blockchain technologies because it ensures that no single entity can have control over the data. On public blockchains, especially in the cryptocurrency applications, incentives are provided for network participants as rewards for discovering new blocks (generating the block's hash function). The user (miner) that submits the valid block is rewarded using a token specific for each platform. These tokens can be used in further transactions on the blockchain or even be exchanged for fiat currency. This method of submitting and verification of new blocks (consensus) is called proof of work (POW).

Ethereum and Smart Contracts
With the rapid development and adoption of the Bitcoin model, the need for an automated transaction model was evident. In 2014, the Ethereum platform was launched, introducing smart contracts to the blockchain [21]. The term smart contract was first introduced in [22] as a set of promises, defined in digital form, including the protocols within which the parties will perform them. Ethereum uses the same basic consensus mechanism of POW where the network nodes continuously mine new blocks by means of their hash function. Similar to Bitcoin, a network token is used as an incentive for the network participants, rewarding the node who successfully generates a valid block by a number of tokes (ETH). To support this reward system and keep the network running, any participant who submits a transaction to the blockchain pays a fee, called gas, in the same way that banks charge their clients a transaction fees for their operations.
Transactions on the Ethereum blockchain can be created either externally or by smart contracts, introducing the concept of functions to the blockchain [21]. Smart contracts are programs that are recorded and verified on the blockchain ( Figure 2). Once the contract is deployed, its code cannot be altered, thus ensuring that the initial conditions will always be respected for any future executions. Just like real world contracts, a smart contract on the blockchain is created between two parties and is executed once some triggering event is set, such as a deadline or a specific target value being reached. In [23], the architecture and applications of blockchain smart contracts are described. Many blockchain implementations provide languages for the development of smart contracts to a certain extent of Turing-completeness. Ethereum, the most popular platform for smart contract and decentralized apps (dApp) development, introduced Solidity, a Turing complete language that allows the creation and deployment of smart contracts on the blockchain [21]. The code of the smart contract is written and compiled using the available language for each specific platform. A contract can have two main attributes: value and state [23]. Once the contract has been created and deployed, users can create calls (execute) to the contract functions. These calls can either query the contract state (read operations) or make changes which will result in a different state (write operations).
In Ethereum a very important difference must be made between these two types of functions. Calling (reading) a contract function is processed immediately, since they are executed locally without consulting the network, by accessing the current state of the blockchain. For this reason, calls do not require gas for their execution (they do not involve any fees).
Verified transactions have the potential (although not mandatory) to change the state of the contract (writing data). These types of executions must be validated by the entire network and the new state of the contract must be agreed upon. Since the data are processed by the entire network, these function calls require gas, which is determined by the number of computational steps and the amount of data which is handled by the contract [21]. These transactions are included in blocks (mined),data are and the change is reflected on the network once the new block is added to the blockchain (a new consensus is reached).
When a verified transaction is submitted it can have the following outcomes based on the amount of gas that is assigned for the transaction [21]:

•
The transaction is executed successfully. In this case the amount of gas that was required by the processing of data is subtracted from the sender's account and transferred to the mining nodes (which verify and process the transaction). If the sender allocated more gas than was actually required, the difference is returned to the sender's account.

•
The transaction exceeded the gas limit set by the sender (the number of computational steps or the amount of data were too high for the fees which the sender was willing to spend). In this case all changes to the contract are reverted. However, the gas is still subtracted from the sender, since the other nodes have executed the code up to a certain point.
On a privately owned network, the gas limit and cost can be controlled so that the users do not run into these problems or their impact will be reduced. Furthermore, for specific applications, a possible solution to the gas-related costs could be the implementation of a semi-decentralized (permissioned) blockchain, where the cost of gas (processing) can be supported by one or more trusted nodes. This will be the network topology proposed in this paper.

IOTA Tangle
Since the blockchain consists of a series of blocks linked together by means of their cryptographic hash, when the number of transactions increases, the difficulty of the hash function also increases, which means that the creation of new blocks will require longer times and greater processing power [24]. This is currently one of the main drawbacks of public blockchain networks. The so-called mining operation is a required mechanism to achieve consensus between all participating nodes. To overcome the resource intensive protocols that are implemented by most platforms, various other consensus methods have been proposed. In [25], a comprehensive study of available and proposed consensus methods is presented. Regardless of the consensus mechanism employed, the scalability of the blockchain will still remain an issue due to the linear fashion in which the data are stored. For data-driven systems, which require a large number of data points, such as IoT applications, this limitation may become an issue. To overcome this issue a novel approach was introduced by the IOTA foundation [26].
The IOTA network was specifically designed with IoT applications in mind, proposing a different method of organizing the transaction data, by using a directed acyclic graph (DAG) instead of a linear blockchain. The IOTA DAG is often referred to as the tangle. Its main characteristic is that it allows zero-fee and zero-value transactions [26] (Figure 3a).
IOTA uses a trinary representation of data, as opposed to the usual binary system. Balanced trinary data can have the following states: 0, 1, or −1 (trits). Similar to how 8 bits form a byte, in IOTA 27 3 3 from a tryte. IOTA uses special trinary hashing functions for data encoding and POW, which are described in [26].
In the usual blockchain implementation, the users have to perform the POW continuously until a hash is successfully found. This is a power-intensive operation that discourages new users from competing in the mining phase. In IOTA, each new transaction (tip) is attached to two previous transactions that it must validate by performing the necessary POW. In this manner, POW is only necessary when a node wants to create a new transaction on the network, thus validating two previous transactions. This means that the node that actually initiates the transaction is the one that computes the POW hash. This allows the elimination of network fees, since it is in the interest of the initiating node for its transaction to be completed. Hence, the network fee is replaced by the "on-demand" POW computation. Since a new transaction validates two previous transactions, the scaling problem can be successfully solved, because more transactions on the network result in more validated transactions.
Once a new transaction is attached to the tangle it also confirms all the previous transactions referenced by the two former tips to which it was attached. This creates a validation path (Figure 3b), which increases the trust for all the transactions inside this path. The IOTA network employs a Markov chain Monte Carlo (MCMC) method of choosing the tips to which the new transaction is attached [26].

Electric Vehicles Batteries and SOC Estimation
The battery is the single most important component in an EV. Most of the weight of an EV comes from the battery pack, so an efficient battery system, together with an optimized consumption model, are crucial in electric vehicle development. Most EV models use lithium-based batteries (lithium-ion, lithium-polymer, lithium-iron-phosphate) [27,28].
The energy requirements and number of battery-operated systems have changed drastically over the last decade. Thus, a real battery management system is required for most battery-operated applications and appliances. One of the most important parameters of a battery is the state of charge (SOC), which represents the available battery capacity. SOC can be influenced by a very large number of factors: battery chemistry, age, temperature, load characteristics, etc.
State of charge estimation methods vary depending both on the type of battery and on the application where it is used. In [29], various methods of SOC estimation and their applications were presented. The authors concluded that the most used technique is the Ampere-hour counting, because of its ease of implementation and good-enough results, but other methods, such as linear modeling, Kalman filter, or artificial intelligence could be used, provided that the system can provide the necessary computational resources or training data.
In [30,31] the authors compared the available methods for lithium-ion batteries with specific applications for EVs. According to the authors, the best-suited methods for EV applications are the electrical circuit model (ECM) or the Kalman filter (KF) model. Machine learning and artificial intelligence models, although very accurate, are not well suited to the field of EV due to the high computational costs involved.
In this section two methods will be briefly presented: the Ampere-hour (Ah) counting and the open circuit voltage (OCV) estimation.

Ampere-Hour Counting SOC Estimation
The Ah counting (or Coulomb counting) method has become an industry standard and one of the most used methods for SOC estimation, because of its accuracy for short-term calculations [30]. The Ah method defines the SOC as: where SOC (t 0 ) is the initial state of charge, C n is the nominal capacity and I battery is the charging or discharging current of the battery [30]. The method is very simple, but it does not take into account the loss current. If the battery current is measured incorrectly, the method will accumulate the measuring errors. This can be compensated by better measuring techniques and sensors.
Taking into account the loss current, Equation (1) could be rewritten as: where I loss is the current consumed by loss reactions [31].
In order to use this method, the initial SOC must be known. If it is not known, or it is incorrectly estimated, the errors will accumulate throughout the process. This method is generally used in combination with other methods to improve the estimated result.

Open Circuit Voltage SOC Estimation
The OCV method uses the battery open circuit voltage as a function of the SOC by means of a polynomial equation or look-up table. The SOC is determined as a reverse function of OCV [30]: The open circuit voltage is continuously measured and the corresponding SOC is obtained using a look-up table specific for each battery type. The accuracy of the method can be very good if enough rest time is provided to estimate the SOC. Therefore, it is not ideal for real-time operation. The method can be used to calibrate the Ah counting Equation (1). Different OCV measurements can be obtained for the same battery under different charging or discharging currents, so the method may not always provide the same result, depending on the C-rates of the charging/discharging process [30].
In the following sections the OCV method is used for SOC estimation, because of the available battery data (look-up tables and empirical measurements). The proposed blockchain application will base its logic around the computed SOC values that can be improved by different estimation methods and measurement techniques.

System Diagram
The proposed battery swapping and charging system is described in Figure 4. Each EV will have an on-board computer, which will monitor the battery data and send the information to the BMS application. Since the on-board computer may not have sufficient resources for computing the POW hashing functions, the charging stations will act as peers on the implemented blockchain and the transactions will be handled by the stations (computing the necessary POW).
The users can register on the system, add new batteries, and create charge or swap requests. These requests are handled by a smart contract and are deployed on the network.
Two blockchain implementations will be implemented and analyzed: a customized Ethereum blockchain (Section 4.4) and the IOTA tangle (Section 4.5).

Battery Level and SOC Monitoring
For the purpose of developing and testing the application, lithium-polymer (LiPo) batteries were used because of their high current and discharge rates, which make them a common solution for EV battery packs.
The chosen SOC estimation method is the OCV. The voltage-SOC table (Table 1) was created using available LiPo look-up tables and checking them empirically.
To extend the life of the battery pack and to avoid deep discharging of the battery [32], it is recommended to remain outside the highlighted area. The data were mapped with a minimum safe battery voltage (V min ) of 3.5 V/cell (7.0 V/cell for two cells and 10.5 V/cell for three cells). Three approximations [33] were considered: linear, symmetric sigmoidal, and asymmetric sigmoidal. The highlighted values represent the unsafe battery operating range.
The linear approximation is described by the following relation: where V is the battery voltage, V max is the maximum voltage (for 100% charge), and V min is the minimum safe voltage, as described in the previous paragraph. The symmetric sigmoidal approximation was fitted using a 4-parameter logistics function (4PL): where: and the parameters a, b, c, and d have the following meaning: a and d control the position of the horizontal asymptotes (upper and lower, respectively), b controls the slope of the response, and c controls the position of the transition region [34]. The asymmetric sigmoidal approximation was fitted using a 5-parameter logistics function (5PL): where a, c, and d are defined in (5) and V normalized is defined in (6). In this case, the b parameter solely controls the approach to the top asymptote and together with g controls the approach to the bottom asymptote [34].
Using curve fitting tools, the parameters for the 4PL function were determined as: a = 0, b = 2.9, c = 1/1.9, and d = 112. With these values, Equation (5) becomes: In the case of the 5PL function the parameters are: a = 0, b = 8, c = 1/3.5, d = 270, and g = 0.045. With these values Equation (7) becomes: The voltage data in Table 1 are plotted together with the three approximations in Figure 5 for a 2-cell battery, with V max = 8400 mV and V min = 7000 mV. In the next section the 4PL approximation is chosen, as it requires less computational effort with very good results.

Battery Monitoring System
The battery monitoring system should be available on any registered EV. For this application, the BMS measures the battery voltage and, using Equation (8), estimates the remaining charge. The data are processed by a micro-controller and sent via I2C (inter-integrated-circuit) communication to an on-board computer (in this case a Raspberry Pi), which generates the transaction and submits the data to the blockchain network.
A monitoring board ( Figure 6) was designed and implemented. An ATMega164p micro-controller is used to measure the battery voltage and compute the SOC using the 4PL approximation (8).
The board monitors all four test batteries simultaneously, which can also power the microcontroller using the power switch. The battery voltages are read from the analog pins of the microcontroller (A0-A3). Since the battery voltages are higher than the 5V accepted by the microcontroller, the voltage is adjusted using voltage dividers.
For the 3-cell batteries the voltage dividers are formed using R1 and R2 (R3 and R4 for the second battery), providing a ratio of 3.12. The divider ratio for the 2-cell batteries is 1.68 (R5 and R6 for the 3rd battery and R7 and R8 for the 4th). For the 3-cell batteries the read voltage ranges between 0 and 4.03 V and for the 2-cell batteries between 0 and 5 V.
The microcontroller transmits the data to the Raspberry Pi via I2C communication. The data are averaged over a series of 60 samples and the blockchain transaction is created. The anatomy of the transaction depends on the blockchain implementation and will be detailed in the following sections.
A battery test bed was designed and implemented (Figure 7), using a Raspberry Pi as an on-board computer for collecting the battery data and relaying the information to the blockchain. The transactions are created using the Python libraries Web3.py (Ethereum) and PyOTA (IOTA). These libraries implement the necessary functions for creating and submitting the transactions for their respective networks. The methods for each implementation will be described in their respective sections below.
For user interaction, a web application has been developed using NodeJS and the libraries specific for each platform (Web3.js for Ethereum and iota.js for IOTA). The web application allows the users and stations to register on the network, add new batteries and manage their requests.
The overall system architecture is presented in Figure 8.

Ethereum Blockchain
The first implementation of the charging/swapping application uses a smart contract deployed on a custom Ethereum blockchain.
In Ethereum, participating nodes have to perform POW to discover new blocks. To motivate users into participating in the block discovery process, a transaction fee (called gas) is paid by the user submitting the transaction. On the public chain the gas cost can be very high depending on the payload of the transaction. This makes the public Ethereum chain not well suited for data transactions, such as IoT applications.
On a customized chain, the gas cost and difficulty of the hash function can be controlled, in order to be used for specific applications, such as the battery management of electric vehicles.
On the main network any user with sufficiently capable processing resources can join. In a custom deployed network user access can be handled according to the application needs, thus allowing the implementation of permissioned blockchains.
In this paper, a permissioned network is created where the registration of new users or charging stations is handled by a master node. This creates a semi-decentralized network, but it can provide certain advantages, which will be highlighted in this section.
Users of the network are the EV owners. The EV computer (Raspberry Pi in this study) will sync to the network in light mode, where only the current state of the network and block headers are synced. For all processing operations a light node depends on the full node peers on the network (it does not take part in the mining process). The semi-decentralized structure ensures that there is at least one full node that is the master node of the application. Transactions and the necessary POW are handled by the charging/swapping station nodes, which will be synced as full nodes on the network.
When a user or station registers on the network via a web application, the master node creates a new address on the blockchain, which will be used to identify the user. The newly created address is stored and managed by the master node.
The registration process is handled by a smart contract deployed on the network. The proposed smart contract is described in Figure 9. The user management section provides the functions for registering new users or stations and for displaying their information.
The user and station information are stored inside the smart contract using the following structure: struct User { uint id ; uint balance ; // user balance uint8 userType ; // user or station bool set ; // differentiate between unset and zero struct values } Upon registration, each user will have a unique id generated (similar to the primary keys in relational databases) and it can have an initial balance of virtual tokens that can be used to perform transaction on the network. The userType field specifies if the user is an EV owner or a charging station.
Each user or station is associated with an address by using a special mapping type, which maps the user address to the user data. All users can be accessed through the user variable.

mapping ( address = > User ) public users ;
The newUser function has the following prototype: function newUser ( address _address , uint8 _type ) public The function checks if a user with the specified address exists. If the address is not found, a new user object is created and its mapping is assigned. The newUser transaction is shown in Table 2 and the result is described in Table 3. The new user has an initial balance of 50 tokens.
In Table 2, the From address is different from the new user address (in the Decoded input field). The From address is the address of the master, as this is the node that actually creates the transaction. In this way, the gas cost required by the transaction is actually paid by the master instead of the user.
The gas used for this transaction would correspond to 0.00234 ETH on the main Ethereum network. For an ETH price of 258 USD (as of May 2019) the transaction cost would be around 0.60 USD. By running a separate network and allowing only mining nodes to submit transactions, the user is not required to have an actual Ethereum token (ETH) balance. Table 3 shows that for a call (read) operation, there is no cost involved, as the function only queries and returns the user data. Table 2. New user transaction on the Ethereum blockchain.
Transaction hash call 0x468fa9e5c2e87816688bcc96176bbe3e711ea4be 0x6b2010a939adce6728d0e61d68c14d19c797a380 0xa87430ba00000000000000000000000062650b2f80d471d29372a4be9acf28365cd419c1 From 0x468fa9e5c2e87816688bcc96176bbe3e711ea4be To

Decoded output
{ "0": "uint256: id 0", "1": "uint256: balance 50", "2": "uint8: userType 0", "3": "bool: set true" } Once users are registered they can add new batteries for their EVs. The battery information is stored in a structure as follows: The newBattery function has the following prototype: function newBattery ( address _address , bytes32 _manufacturer , bytes32 _model , bytes32 _batteryType , uint32 _capacity , uint8 _cells , uint256 _manufactureDate , uint32 _ ma x Ch ar g eC ou n t ) public The function requires the battery owner's address (which was provided after registering) and the battery information. The resulting transaction is presented in Table A1. Since the amount of data written to the contract is much higher than the newUser transactions, the gas cost is almost double.
When a battery runs low, the user can manually submit a charge or swap request to the contract newRequest method (Table A2): function newRequest ( address _address , uint _batteryId , uint8 _requestType , uint _timestamp ) public The _requestType parameter specifies if it is a charge or swap request. Note that the request does not specify a specific station. All stations can view the request and whichever one can provide the requested service can accept it (Table A3). The function acceptRequest has the following definition: function acceptRequest ( address _address , uint _userIndex , address _station , uint _stationIndex , uint _approved ) public where the _address and _userIndex represent the user address and their battery identifier is used to locate the battery in the structure mapping; the _station and _stationIndex are used to specify the station's battery and the _approved parameter is the timestamp of the approval. The function changes the owners of the two batteries and the change will be reflected on the network once the transaction is confirmed. The result after the request is accepted is presented in Table A4.
The previous requests are created by the users/stations using the web interface. The battery information is submitted by the on-board computer and the data are stored in the smart contract using the following structure: where the _address, _id, and _index parameters are used to identify the user and the battery, _voltage and _soc are the actual measurements, and _chargeCount and _timestamp are the current charge count and the date and time of the measurement. In this section, a full implementation of a battery swapping/charging system is described, using an Ethereum smart contract on a custom network. This approach allows further actions or improvements to be added to the smart contract, while the transaction costs are supported by the master node due to the semi-decentralized, permission-based approach.
Using the same contract on the main Ethereum network would be unfeasible, due to the high transaction costs (gas). The nature of the application is perfectly suited for a permission-based network, since the aim of the application is to transfer data rather than tokens on the blockchain.

IOTA Tangle
The Ethereum implementation uses the power and flexibility of smart contracts to implement the application logic on the blockchain ensuring that all nodes run the same code and data immutability.
The first difference between IOTA and other blockchain platforms is the way the data are stored (directed acyclic graph vs. linear chained blocks). This solves the scalability issue by linking a new transaction to two previous transactions by validating them, as described in Section 4.5.
Since the IOTA network does not have transaction fees, the implementation can run on the public network. One important disadvantage is that IOTA does not (yet) support smart contracts, and thus the application logic has to be handled by a master node, resulting in a semi-decentralized system. In this case, the master node has to perform extra operations to extract and filter the data from the tangle, whereas in the Ethereum version these operations were handled directly by the smart contract functions.
To implement the required functionality, the transaction structure is used (Table 4) by routing the different types of transactions to their specific actions. To route the transaction to specific actions, the tag field is used, similar to a function call of a smart contract. Based on this the application will filter the data and assign it to the appropriate structures.
For example, the equivalent of the newUser operation from the Ethereum implementation would have the structure described in Table 5.
The tag field specifies the action of the transaction. Since the application is running on the public development network, any user can create a transaction with this tag. However, since all transactions are still handled by the master node as the sender, the application will only filter its own transactions from the tangle.
Since the IOTA implementation uses only raw transactions, their structure for the other operations are similar to the one presented in Table 5. Each operation has a corresponding tag field: IOTABMSNEWUSER for the new user transactions; IOTABMSNEWBATTERY for the new battery operation; IOTABMSNEWDATA for battery data information; and IOTABMSNEWREQUEST and IOTABMSACCEPTREQUEST for the request operations. Because the IOTA implementation uses the public Devnet tangle, these tags can be used to examine the transaction details at https://devnet.thetangle.org.
For this implementation, the monitoring board collects the data over 60 samples, at the same rate of 30 samples/minute. The data are stored directly on the tangle, so the Raspberry Pi has to create a new transaction using the ProposedTransaction class from the PyOTA Python library: where IOTAAddress is the address of the master node and IOTAJSONData is a JSON object containing the measurement information, with the same properties as the newData function from the Ethereum implementation. The ProposedTransaction object is a transaction that was created locally and has not yet been submitted to the network. To actually broadcast the transaction, the send_transfer function is used: , m i n _ w e i g h t _ m a g n i t u d e = 14 , inputs = Batt eryAdd ress ) where BatteryAddress is the address of the registered battery (acting as the sender of the message), depth is the maximum depth in the tangle for the tip selection mechanism, and min_weight_magnitude is an optional parameter used to specify the POW difficulty. Note that the transfers parameter contains a list of transactions (in this case only one), since there is no value transferred between the two addresses. When transferring IOTA tokens, at least two transactions are required: one that adds tokens to the recipient and one that subtracts the same amount from the sender.
Ideally, the POW should be performed locally. However, the Raspberry PI does not have the necessary resources to compute the POW, so the transaction is handled by the master node of the system, which computes the validation hashes for two selected tips. If the master node is not reachable, the transaction data are stored locally and resubmitted when the connection can be established.
The biggest challenge and limitation of this implementation is the battery swapping operation. Since the swap request is not sent to a particular station (similar to the Ethereum implementation), the station that accepts the request has to do so by creating a new transaction. This new transaction has to somehow reference the swap request submitted by the user. Two solutions can be outlined for this problem: either reference the swap request transaction hash in the message field of the transaction, together with the rest of the information, or override the IOTA's tip selection mechanism and attach the acceptRequest transaction directly to the related request transaction using the trunkTransaction or branchTransaction fields (Table 4). For this implementation, the first method was preferred.
The main difference between the IOTA implementation and the Ethereum one is that the code which handles the data storage and processing is not contained in a smart contract (distributed across all nodes), but runs solely on the master node. This makes the IOTA implementation more centralized than its Ethereum counterpart, due to the fact that the master node still represents a single point of failure for the application.

Decoded message
{ "address": "SMVIZBPLNB. . . MRSWJCDZKD", "type": "0", "balance": 50, "timestamp": "1558442329142" } In the case of smart contracts, the corresponding function is executed whenever a transaction is submitted. In the IOTA implementation the master node has to monitor the network state continuously using the transaction tag field and decide which function should be executed locally. Here, the tangle is used only as a decentralized data storage (instead of a traditional database management system). When the user wants to access the information from the web application, the master node queries the tangle for the raw data and any necessary processing is done before presenting the data to the user.
Off-chain processing is recommended when working with distributed applications, since computational power is expensive on any blockchain implementation, but it is much more difficult to work with unstructured data than with organized data structures achieved through smart contracts.
One important difference between the IOTA implementation and the Ethereum counterpart is the fact that Ethereum requires at least two full nodes (the master node and at least one charging station) to perform the POW and create new blocks on the network. In IOTA, the charging stations can be connected to the tangle, but this is not mandatory, since the actual POW is done by the device that creates the transaction (the master node in this implementation). This reduces the setup time and the necessary hardware requirements for the stations, but has the downside that if the master node is not available, the system may encounter some down-times. 10 and 11 show the voltage and state of charge plots for a 2-cell and 3-cell battery, respectively. These results are obtained directly in the front-end application and can be viewed by the users. They can help improve the SOC estimation by accounting for battery age and other environmental factors, and possibly allow stations or users to properly service or replace batteries in safe operating conditions. It can be noted that the SOC vs. Voltage plot (Figures 10c and 11c) is similar to the theoretical 4-PL approximation in Figure 5b, which is the expected result. To compare the two implementations, the transaction times were measured for a set of 500 transactions submitting new battery data ( Figure 12). For the Ethereum blockchain (Figure 12a), running with two mining nodes (one master node and one charging station), the time from submitting a transaction until its first confirmation by the network ranged between 1.65 and 75.45 s, with an average of 12.97 s per transaction. These confirmation times can vary depending on the network congestion, the number of operations required in the contract function and the difficulty of the network, which, in the case of a permission-based chain, can be controlled by the network administrator. For the IOTA tangle the results for the same transactions are presented in Figure 12b. It can be seen that the transaction times are slightly higher than the Ethereum implementation, with an average of 17.86 s and the minimum and maximum values of 3.78 and 104.14 seconds, respectively. These differences can be easily explained by the different approach of the two platforms. While in Ethereum, mining nodes perform the POW operations continuously, in IOTA these operations are performed only when a new transaction is submitted. In the proposed implementation the IOTA POW is not done locally due to the limited resources of the Raspberry Pi board. Instead, the required operations are performed by a public node outside the application infrastructure (in this case, the IOTA Devnet node).

Figures
Depending on the load of the node and the network congestion, the expected transaction recording time can vary. However, the benefit is an easier setup and fewer resources necessary for the master and station nodes of the BMS application.

Discussion
The Ethereum blockchain demonstrates that the technology is mature enough to be used in many fields of industry, offering the possibility of developing any kind of application logic on the blockchain in a decentralized manner. The main disadvantage of this approach is the rather complicated setup required to deploy the blockchain and smart contract. Since the application would not be suited to function on the main network, due to the high transaction fees, the creation of a separate network is absolutely necessary. Hence, one advantage is the possibility to manage the network settings and difficulty, so that the response time can be reduced, compared to a transaction on the public blockchain. Another advantage, which will be considered in future works, is to setup the blockchain using a different consensus mechanism, such as proof-of-authority (POA), where designated nodes can add new blocks to the chain without requiring a swarm of mining nodes.
IOTA was considered as an alternative because of its zero-fee transaction model and its scalability, which allows the application to run on the main tangle with minimal additional setup. The lack of smart contracts is the main disadvantage of this approach, because the application logic has to be maintained by one or more central nodes and it is more susceptible to failures, while possible changes of the application may affect its overall functionality on the network. These problems could be resolved when smart contracts become available in IOTA (which were already announced as of 2019), but the implementation may provide additional difficulties that cannot yet be estimated.
The main problem of the proposed IOTA implementation is the tag-based routing system, which can be replicated by users not registered on the battery management application. This can be solved either by having one or more trusted nodes (or oracles) that will generate the transactions on behalf of their users (as proposed in this paper), or by using masked authenticated messages (MAM) [35] as a means to create direct channels of communication between data publishers (EV owners) and subscribers (stations). This approach will be further studied in future works.
Battery charging requests on IOTA can be easily created because they do not involve changing the ownership of the battery, but, without the capabilities of on-chain processing, swap requests can be more difficult to handle, as they require the front-end application to search through the transaction history to find the latest state of the requested batteries. Due to this fact, IOTA is better related to producer-consumer applications, where sensors or embedded devices are the data producers and the users query and use the data off-tangle (data flow is unidirectional).
An issue for any application which relies on user information and value exchange (tokens, electricity, batteries, fiat currency, etc.) must deal with the privacy issues that may arise from these interactions. Several methods can be considered, depending on the type of blockchain that is being used and on the visibility of the blockchain network. Feng et al. [36] and Jia et al. [37] introduced such methods that deal with blockchain privacy.
The Ethereum-based implementation presented in this paper uses a private blockchain network where user access control (UAC) methods can be implemented to protect the user information. Furthermore, sensitive user information can be encrypted using a private-public key mechanism.
The proposed IOTA implementation uses the public tangle; thus, MAM can be used to establish a direct channel between the involved parties when an exchange is requested (battery swap or driver-to-driver charging).
These issues are an interesting extension for this study and the authors plan on extending the results of the current paper with an in-depth study on blockchain data privacy and protection.

Conclusions
In this paper, a complete battery management system for electric vehicles was presented using blockchain technology to create a semi-decentralized network of electric vehicles and charging stations that are able to share data (battery information and condition) based on continuous monitoring.
Blockchain is a relatively young technology that has seen major growth and adoption in the last 10 years with the development of cryptocurrencies. The underlying architecture makes it a strong candidate for data-driven applications, such as electric and autonomous vehicles.
To analyze the feasibility of the proposed application, two distinct implementations were considered and tested: the first method uses an Ethereum blockchain, powered by a smart contract, which allows the distributed processing and sharing of data, while at the same time ensuring data immutability and privacy. The second approach uses the IOTA network, which lacks the support for smart contract development, but provides zero-fee transactions and is built with data-driven applications in mind, thus allowing better application scaling.
The results show that both platforms can be used for developing blockchain IoT applications having acceptable transaction confirmation times for the purpose of the proposed battery monitoring system, which does not require real-time confirmations. Ethereum is still the main platform for developing decentralized applications, which can be deduced from the large number of projects and research papers available. This may change in the future especially for IoT and data-driven applications, as alternative approaches specially designed for this field mature and become available.

Conflicts of Interest:
The authors declare no conflict of interest.

Abbreviations
The following abbreviations are used in this manuscript:  Table A1. New battery transaction on the Ethereum blockchain.