code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="footer"> <div class="wrapper"> <div class="footbox"> <h2>About</h2> <ul> <li><a href="#">CloudCom</a></li> <li><a href="#">Events</a></li> <li><a href="#">Announcements</a></li> <li><a href="#">Blogs</a></li> <li class="last"><a href="#">Contacts</a></li> </ul> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Premium Support</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Forums</a></li> <li><a href="#">Discussion</a></li> <li class="last"><a href="#">Support</a></li> </ul> </div> <div class="footbox"> <h2>Developers</h2> <ul> <li><a href="#">Java</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li class="last"><a href="#">.Net</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Case Studies</a></li> <li><a href="#">Whitepapers</a></li> <li><a href="#">Seminars</a></li> <li><a href="#">Tutorials</a></li> <li class="last"><a href="#">Webminars</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 2012 - All Rights Reserved - <a href="#">www.cloudcom.com</a></p> <p class="fl_right"><a href="#">Reference OS Template</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
tail.html
HTML
gpl3
1,867
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> <script type="text/javascript"> var xmlhttp; var userID; var i; function deleteUser(){ var userIDRB = document.admin.userID; for(i = 0; i < userIDRB.length; i++){ if(userIDRB[i].checked){ userID = userIDRB[i].value; break; } } // alert(userID + " is clicked"); // alert(userID); if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReply; xmlhttp.open("GET", "deleteUser.php?userID="+userID, true); xmlhttp.send(); } function handleReply(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); userTable = document.getElementById("userTable"); userTable.deleteRow(i+1); } } </script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "administrator")){ echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; echo "<br/>Welcome administrator"; // put your code here $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from users"); echo "<form method='post' name='admin' action='updateUser.php'>"; echo "<table border='1' id='userTable'> <tr> <th>Username</th> <th>Password</th> <th>First name</th> <th>Last name</th> <th>DOB</th> <th>User type</th> <th>Select</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["username"]."</td>"; echo "<td>".$row["password"]."</td>"; echo "<td>".$row["firstName"]."</td>"; echo "<td>".$row["lastName"]."</td>"; echo "<td>".$row["dob"]."</td>"; echo "<td>".$row["userType"]."</td>"; echo "<td><input type='radio' name='userID' value='".$row["userID"]."'/></td>"; echo "</tr>"; } echo "</table>"; ?> <input type="submit" value="Add or Change User" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="button" value="Delete User" class="buttonStyle" onclick="deleteUser()" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <?php echo "</form>"; mysql_close($con); }else{ // echo $_SESSION["userType"." ".$_SESSION["userID"]]; require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
admin.php
PHP
gpl3
4,196
<?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; echo "<br/>Welcome ".$_COOKIE["username"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> <script type="text/javascript"> var xmlhttp; function showProduct(){ // alert("zhouzhao"); var productName = document.product.productName.value; var categoryID = document.product.categoryID.value; var minPrice = document.product.minPrice.value; var maxPrice = document.product.maxPrice.value; // alert(productName); if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyProduct; xmlhttp.open("GET", "showProduct.php?productName="+productName+"&categoryID="+categoryID+"&minPrice="+minPrice+"&maxPrice="+maxPrice, true); xmlhttp.send(); } function handleReplyProduct(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); document.getElementById("productResult").innerHTML = xmlhttp.responseText; } } function showUser(userType){ if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyUser; xmlhttp.open("GET", "showUser.php?userType="+userType, true); xmlhttp.send(); } function handleReplyUser(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); document.getElementById("userResult").innerHTML = xmlhttp.responseText; } } function showSale(){ var productName = document.sale.productName.value; var categoryID = document.sale.categoryID.value; var minPrice = document.sale.minPrice.value; var maxPrice = document.sale.maxPrice.value; var startDate = document.sale.startDate.value; var endDate = document.sale.endDate.value; if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplySale; xmlhttp.open("GET", "showSale.php?productName="+productName+"&categoryID="+categoryID+"&minPrice="+minPrice+"&maxPrice="+maxPrice+"&startDate="+startDate+"&endDate="+endDate, true); xmlhttp.send(); } function handleReplySale(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); document.getElementById("saleResult").innerHTML = xmlhttp.responseText; } } function showCategory(){ var categoryName = document.category.categoryName.value; if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyCategory; xmlhttp.open("GET", "showCategory.php?categoryName="+categoryName, true); xmlhttp.send(); } function handleReplyCategory(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); document.getElementById("categoryResult").innerHTML = xmlhttp.responseText; } } function showOrder(){ var productName = document.order.productName.value; var categoryID = document.order.categoryID.value; var startDate = document.order.startDate.value; var endDate = document.order.endDate.value; if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyOrder; xmlhttp.open("GET", "showOrderManager.php?productName="+productName+"&categoryID="+categoryID+"&startDate="+startDate+"&endDate="+endDate, true); xmlhttp.send(); } function handleReplyOrder(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); document.getElementById("orderResult").innerHTML = xmlhttp.responseText; } } </script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "manager")){ ?> <form name="product"> <p>Product name: <input type="text" name="productName" maxlength="20" class="rightAlign"/></p> <p>Product category: <input type="text" name="categoryID" maxlength="20" class="rightAlign"/></p> <p>Product min price: <input type="text" name="minPrice" maxlength="10" class="rightAlign"/></p> <p>Product max price: <input type="text" name="maxPrice" maxlength="10" class="rightAlign"/></p> <input type="button" value="Search product" onclick="showProduct()" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form><br/> <div id="productResult"><b>Product result will be listed here ...</b></div><br/> <form name="user"> <select name="userType" onchange="showUser(this.value)"> <option value="all">All</option> <option value="administrator">Administrator</option> <option value="seller">Seller</option> <option value="manager">Manager</option> </select> </form><br/> <div id="userResult"><b>User result will be listed here ...</b></div><br/> <form name="sale"> <p>Product name: <input type="text" name="productName" maxlength="20" class="rightAlign"/></p> <p>Product category: <input type="text" name="categoryID" maxlength="20" class="rightAlign"/></p> <p>Sale start date: <input type="text" name="startDate" maxlength="20" class="rightAlign"/></p> <p>Sale end date: <input type="text" name="endDate" maxlength="20" class="rightAlign"/></p> <p>Product min price: <input type="text" name="minPrice" maxlength="10" class="rightAlign"/></p> <p>Product max price: <input type="text" name="maxPrice" maxlength="10" class="rightAlign"/></p> <input type="button" value="Search sale" onclick="showSale()" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form><br/> <div id="saleResult"><b>Sale result will be listed here ...</b></div><br/> <form name="category"> <p>Category name: <input type="text" name="categoryName" maxlength="20" class="rightAlign"/></p> <input type="button" value="Search category" onclick="showCategory()" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form><br/> <div id="categoryResult"><b>Category result will be listed here ...</b></div> <form name="order"> <p>Product name: <input type="text" name="productName" maxlength="20" class="rightAlign"/></p> <p>Product category: <input type="text" name="categoryID" maxlength="20" class="rightAlign"/></p> <p>Order start date: <input type="text" name="startDate" maxlength="20" class="rightAlign"/></p> <p>Order end date: <input type="text" name="endDate" maxlength="20" class="rightAlign"/></p> <input type="button" value="Search order" onclick="showOrder()" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <div id="orderResult"><b>Order result will be listed here ...</b></div> <?php }else{ /*Managers get new reports to see all about orders. They are to be able to retrieve orders, and summaries of product sold by date, by product category, by special sales items, or by product. Note: A single request could provide values for all three organizing ways. For example, a manager wants the total sales for a specific product category, for a specific time frame they specify. */ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
manager.php
PHP
gpl3
10,848
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> <script type="text/javascript"> var xmlhttp; function changeCategory(category){ // alert(category); if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReply; xmlhttp.open("GET", "changeCategory.php?category="+category, true); xmlhttp.send(); } function handleReply(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ document.getElementById("products").innerHTML=xmlhttp.responseText; } } </script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here echo "Welcome customer ".$_SESSION["firstName"]." ".$_SESSION["lastName"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result1 = mysql_query("select * from categories"); $result2 = mysql_query("select * from products P"); $result3 = mysql_query("select * from products P, sales S where P.productID=S.productID"); ?> <form method="post" name="customer" action="updateCart.php"> Category: <select name="category" onchange="changeCategory(this.value)"> <?php echo "<option value='0'>all</option>"; while($row = mysql_fetch_assoc($result1)){ echo "<option value='".$row["categoryID"]."'>".$row["categoryName"]."</option>"; } ?> </select> <div id="products"> <table border="1" id="productTable"> <tr> <th>Category ID</th> <th>Product name</th> <th>Product description</th> <th>Product image</th> <th>Product price</th> <th>Select</th> </tr> <?php while($row = mysql_fetch_assoc($result2)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td><img src='images/products/".$row["productImage"]."' width='100' heigth='100' alt='image' /></td>"; echo "<td>".$row["productPrice"]."</td>"; echo "<td><input type='radio' name='productID' value='".$row["productID"]."'/></td>"; echo "</tr>"; } mysql_close($con); ?> </table> <table border="1" id="saleTable"> <tr> <th>Category ID</th> <th>Product name</th> <th>Sale image</th> <th>Discount</th> <th>Start date</th> <th>End date</th> </tr> <?php while($row = mysql_fetch_assoc($result3)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td><img src='images/products/sale.jpg' width='100' heigth='100' alt='image' /></td>"; echo "<td>".$row["discount"]."</td>"; echo "<td>".$row["startDate"]."</td>"; echo "<td>".$row["endDate"]."</td>"; echo "</tr>"; } ?> </table> </div> <select name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5+</option> </select> <input type="submit" value="Add to Cart" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php if(isset($_SESSION["customerID"])){ ?> <form method="post" name="logout" action="logout.php"> <input type="submit" value="Logout" class="logoutStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
customer.php
PHP
gpl3
6,191
<?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $saleID =$_GET["saleID"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); mysql_query("delete from sales where saleID = $saleID"); mysql_close($con); echo "$saleID"; }else{ require 'login.html'; } ?>
zzspring2012csci571
deleteSale.php
PHP
gpl3
627
<?php session_start(); $username = $_POST["username"]; $password = $_POST["password"]; $errorMsg = ""; $displayLoginPage = true; setcookie("username", "$username", time()+20); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // login code is here if (strlen($username) == 0 || strlen($password) == 0) { $errorMsg = "Invalid employee login"; } if (strlen($username) == 0 && strlen($password) == 0) { $errorMsg = ""; } //go to DB to validate employee when username and password both exist if (strlen($username) > 0 && strlen($password) > 0) { $sql = "select * from users where username='$username' and password='$password'"; $link = mysql_connect("localhost", "zhouzhao", "19831022"); if (!$link) { die("error: could NOT connect to DB ".mysql_error()); } mysql_selectdb("cloudcom", $link); $result = mysql_query($sql); if(!($row = mysql_fetch_assoc($result))){ //invalid login $errorMsg = "Invalid login<br/>"; }else{ //valid login $errorMsg = "Valid ".$row["userType"]." login<br/>"; $displayLoginPage = false; } mysql_close($link); } ?> <p style="color:red"> <?php // echo $errorMsg; if($displayLoginPage){ require 'login.html'; } ?> </p> <?php $_SESSION["userID"] = $row["userID"]; $_SESSION["userType"] = $row["userType"]; //require 'employee.html'; if(!strcmp($row["userType"], "administrator")){ require 'admin.php'; }else if(!strcmp($row["userType"], "seller")){ require 'seller.php'; }else if(!strcmp($row["userType"], "manager")){ require 'manager.php'; } ?> </body> </html>
zzspring2012csci571
login.php
PHP
gpl3
2,349
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="styles/layout.css" type="text/css" /> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li><a href="index.html">Home</a></li> <li><a href="customerLogin.html">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a> </li> <li class="active"><a href="login.html">Employees</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="breadcrumb"> <div class="wrapper"> <p style="color:red" id="errorMsg">The field with label * is required</p> </div> </div> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <form method="post" name="register" action="register.php"> <p>Username: <input type="text" name="username" class="rightAlign" maxlength="20"/></p> <p>Password: <input type="password" name="password" class="rightAlign" maxlength="20"/></p> <p>First name: <input type="text" name="firstName" class="rightAlign" maxlength="20"/></p> <p>Last name: <input type="text" name="lastName" class="rightAlign" maxlength="20"/></p> <p>Date of birth:<br/> Month: <select name="month"> <option value="0" disabled="disabled"></option> <option value="1">Jan</option> <option value="2">Feb</option> <option value="3">Mar</option> <option value="4">Apr</option> <option value="5">May</option> <option value="6">Jun</option> <option value="7">Jul</option> <option value="8">Aug</option> <option value="9">Sep</option> <option value="10">Oct</option> <option value="11">Nov</option> <option value="12">Dec</option> </select> Day: <input type="text" name="day" maxlength="2"/> Year: <input type="text" name="year" maxlength="4"/></p> <p>User type:<br/> <input type="radio" name="userType" value="administrator" />Administrator<br/> <input type="radio" name="userType" value="manager"/>Manager<br/> <input type="radio" name="userType" value="seller"/>Seller<br/> <input type="submit" value="submit" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/><p> </form> </div> </div> <br class="clear" /> </div> </div> <div id="footer"> <div class="wrapper"> <div class="footbox"> <h2>About</h2> <ul> <li><a href="#">CloudCom</a></li> <li><a href="#">Events</a></li> <li><a href="#">Announcements</a></li> <li><a href="#">Blogs</a></li> <li class="last"><a href="#">Contacts</a></li> </ul> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Premium Support</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Forums</a></li> <li><a href="#">Discussion</a></li> <li class="last"><a href="#">Support</a></li> </ul> </div> <div class="footbox"> <h2>Developers</h2> <ul> <li><a href="#">Java</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li class="last"><a href="#">.Net</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Case Studies</a></li> <li><a href="#">Whitepapers</a></li> <li><a href="#">Seminars</a></li> <li><a href="#">Tutorials</a></li> <li class="last"><a href="#">Webminars</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 2012 - All Rights Reserved - <a href="#">www.cloudcom.com</a></p> <p class="fl_right"><a href="#">Reference OS Template</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
register.html
HTML
gpl3
4,978
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ $username = $_POST["username"]; $password = $_POST["password"]; $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $year = $_POST["year"]; $month = $_POST["month"]; $day = $_POST["day"]; $userType = $_POST["userType"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could NOT connect to DB".mysql_error()); }else{ // echo "DB is connected<br/>"; } mysql_select_db("cloudcom", $con); if(!mysql_query("insert into users values (null, '$username', '$password', '$firstName', '$lastName', '$year-$month-$day', '$userType')")){ die("error: ".mysql_errno()); }else{ echo "New employee $firstName $lastName has been registered<br/>"; require 'login.html'; } mysql_close($con); ?>
zzspring2012csci571
register.php
PHP
gpl3
965
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here $orderID = $_POST["orderID"]; echo "Welcome customer ".$_SESSION["firstName"]." ".$_SESSION["lastName"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from products P, items I where I.orderID=".$orderID." and P.productID=I.productID"); ?> <form method="post" name="item" action=""> <table border="1" id="itemTable"> <tr> <th>Product Name</th> <th>Product Description</th> <th>Product Image</th> <th>Product Price</th> <th>Product Quantity</th> </tr> <?php while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td><img src='images/products/".$row["productImage"]."' width='100' height='100' alt='image' /></td>"; echo "<td>".$row["productPrice"]."</td>"; echo "<td>".$row["productQuantity"]."</td>"; echo "</tr>"; } mysql_close($con); ?> </table> </form> <?php if(isset($_SESSION["customerID"])){ ?> <form method="post" name="logout" action="logout.php"> <input type="submit" value="Logout" class="logoutStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
showItem.php
PHP
gpl3
2,601
<?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head> <title>CloudCom</title> <link rel="stylesheet" href="styles/layout.css" type="text/css" /> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body id="top" onload="initialization()"> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li><a href="index.html">Home</a></li> <li class="active"><a href="cloudcom.php">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a> </li> <li class="last"><a href="login.html">Employees</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="breadcrumb"> <div class="wrapper"> <p style="color:red">The field with label * is required</p> </div> </div> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <!-- The first form for customer info--> <div id="divCustomer" style="display:block"> <?php if(isset($_SESSION["customerID"])){ $customerID = $_SESSION["customerID"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from customers where customerID = ".$customerID); $row = mysql_fetch_assoc($result); mysql_close($con); } ?> <form method="post" name="customer" id="form1" onsubmit="return nextForm()" action="customerRegister.php"> <div class="order"> <h2>Personal Information</h2> <p> <span class="redStar">*</span> First Name: <span class="rightAlign"> <input type="text" name="firstName" maxlength="10" <?php if(strlen($customerID) != 0) echo "value='".$row["firstName"]."'"; ?> /> <input type="image" class="leftAlign" src="images/demo/question.jpg" alt="info" width="20" height="20" onmouseover="fnOver()" onmouseout="fnOut()"/> <span class="comment" id="fnComment">max length of characters is 10</span> <span id="fnMsg" class="comment" style="color:red"></span> </span> </p> <p><span class="redStar">*</span> Last Name: <span class="rightAlign"> <input type="text" name="lastName" maxlength="10" <?php if(strlen($customerID) != 0) echo "value='".$row["lastName"]."'"; ?> /> <input type="image" class="leftAlign" src="images/demo/question.jpg" alt="info" width="20" height="20" onmouseover="lnOver()" onmouseout="lnOut()" /> <span class="comment" id="lnComment">max length of characters is 10</span> <span id="lnMsg" class="comment" style="color:red"></span> </span> </p> <p><span class="redStar">*</span> Email: <span class="rightAlign"> <input type="text" name="email" maxlength="50" <?php if(strlen($customerID) != 0) echo "value='".$row["email"]."'"; ?> /> <input type="image" class="leftAlign" src="images/demo/question.jpg" alt="info" width="20" height="20" onmouseover="emailOver()" onmouseout="emailOut()" /> <span class="comment" id="emailComment">valid email address is required</span> <span id="emailMsg" class="comment" style="color:red"></span> </span> </p> <p><span class="redStar">*</span> Password: <span class="rightAlign"> <input type="password" name="password" maxlength="10" <?php if(strlen($customerID) != 0) echo "value='".$row["password"]."'"; ?> /> <input type="image" class="leftAlign" src="images/demo/question.jpg" alt="info" width="20" height="20" onmouseover="passwordOver()" onmouseout="passwordOut()" /> <span class="comment" id="passwordComment">passwrod must be at least 10 chars</span> <span id="passwordMsg" class="comment" style="color:red"></span> </span> </p> <p><span class="redStar">*</span> Repeat password: <span class="rightAlign"><input type="password" name="repeatPassword" maxlength="10" /> <span id="repeatMsg" class="comment" style="color:red"></span> </span> </p> <p>Home phone number: <span class="rightAlign"><input type="text" name="homePhone1" size="3" maxlength="3" <?php if(strlen($customerID) != 0) echo "value='".substr($row["homePhone"], 0, 3)."'"; ?> /> - <input type="text" name="homePhone2" size="3" maxlength="3" <?php if(strlen($customerID) != 0) echo "value='".substr($row["homePhone"], 3, 3)."'"; ?> /> - <input type="text" name="homePhone3" size="4" maxlength="4" <?php if(strlen($customerID) != 0) echo "value='".substr($row["homePhone"], 6, 4)."'"; ?> /> <span class="comment" style="display:inline">eg. (626)-241-7880</span></span> </p> <p>Cell phone number: <span class="rightAlign"><input type="text" name="cellPhone1" size="3" maxlength="3" <?php if(strlen($customerID) != 0) echo "value='".substr($row["cellPhone"], 0, 3)."'"; ?> /> - <input type="text" name="cellPhone2" size="3" maxlength="3" <?php if(strlen($customerID) != 0) echo "value='".substr($row["cellPhone"], 3, 3)."'"; ?> /> - <input type="text" name="cellPhone3" size="4" maxlength="4" <?php if(strlen($customerID) != 0) echo "value='".substr($row["cellPhone"], 6, 4)."'"; ?> /> <span class="comment" style="display:inline">eg. (626)-241-7880</span></span> </p> </div> <div class="order"> <h2>Home Address</h2> <p>Street:<input type="text" class="rightAlign" name="street" maxlength="20" <?php if(strlen($customerID) != 0) echo "value='".$row["street"]."'"; ?> /></p> <p>City: <select name="city"> <option disabled="disabled">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option> </select> State: <select name="state" onchange="updateCity()"> <option value="-1" disabled="disabled"></option> <option value="0">California</option> <option value="1">New York</option> <option value="2">Texas</option> <option value="3">Massachusetts</option> </select> <span class="redStar">*</span> Zip: <input type="text" name="zip" size="7" maxlength="5" <?php if(strlen($customerID) != 0) echo "value='".$row["zip"]."'"; ?> /><span id="zipMsg" class="comment" style="color:red"></span> </p> </div> <input type="submit" class="buttonStyle" value="Register" id="nextform" onmouseover="changeOn(this)" onmouseout="changeOff(this)" /> </form> </div> <!-- The second form for computer order--> <div id="divComputer" style="display:none"> <form method="post" name="computerForm" id="form2"> <div id="core" class="order"> <h2>Critical Elements</h2> <p> <span class="redStar">*</span> <b>Processor</b><span id="processorMsg" class="message"></span><br /> <input type="radio" name="processor" value="3.3" />3.3GHz <input type="radio" class="rightShift" name="processor" value="3.6" /><span class="rightShiftMove">3.6GHz</span> <input type="radio" class="rightShift2" name="processor" value="3.7" /><span class="rightShiftMove2">3.7GHz</span></p> <p> <span class="redStar">*</span> <b>Memory</b><span id="memoryMsg" class="message"></span><br /> <input type="radio" name="memory" value="6" />6GB <input type="radio" class="rightShift" name="memory" value="8" /><span class="rightShiftMove">8GB</span> <input type="radio" class="rightShift2" name="memory" value="12" /><span class="rightShiftMove2">12GB</span></p> <b>Video Card</b><p id="videoMsg" class="message"></p> <select name="company" onchange="updateVideoCard()"> <option value="-1" disabled="disabled"></option> <option value="0">NVidia</option> <option value="1">AMD</option> <option value="2">Intel</option> </select> <select name="video"> <option value="-1" disabled="disabled">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option> </select> <br /> <p> <b>LCD display</b><span id="lcdMsg" class="message"></span><br /> <input type="radio" name="lcd" value="1" />1600*900 60Hz <input type="radio" class="rightShift" name="lcd" value="2" /><span class="rightShiftMove">1920*1080 60Hz</span> <input type="radio" class="rightShift2" name="lcd" value="3" /><span class="rightShiftMove2">1920*1080 120Hz</span></p> <p> <b>Operating System</b><span id="osMsg" class="message"></span><br /> <input type="radio" name="os" value="home" />Win7 Home <input type="radio" class="rightShift" name="os" value="pro" /><span class="rightShiftMove">Win7 Pro</span> <input type="radio" class="rightShift2" name="os" value="ultimate" /><span class="rightShiftMove2">Win7 Ultimate</span></p> </div> <div id="accessary" class="order"> <h2>Most Popular Add-ons</h2> <p> <b>Monitors</b><br /> <input type="checkbox" name="kvm" value="dell1" />Dell 24'' Full HD <input type="checkbox" class="rightShift" name="kvm" value="dell2" /><span class="rightShiftMove">Dell KM632</span> <input type="checkbox" class="rightShift2" name="kvm" value="dell3" /><span class="rightShiftMove2">Alienware Keyboard</span> </p> <p> <span class="redStar">*</span> <b>Power and Battery</b><span id="powerMsg" class="message"></span><br /> <input type="checkbox" name="power" value="cell1" />240W Power Adapter <input type="checkbox" class="rightShift" name="power" value="cell2" /><span class="rightShiftMove">9-cell Li-ion battery</span> <input type="checkbox" class="rightShift2" name="power" value="cell3" /><span class="rightShiftMove2">12-cell Li-ion battery</span></p> <b>Wireless Router</b><br /> <select name="router" multiple="multiple"> <option value="0">Netgear WiFi0</option> <option value="1">Netgear WiFi1</option> <option value="2">Netgear WiFi2</option> <option value="3">Netgear WiFi3</option> <option value="4">Netgear WiFi4</option> </select> <p> <span class="redStar">*</span> <b>Software</b><span id="softwareMsg" class="message"></span><br /> <select name="software" multiple="multiple"> <option value="Microsoft">Microsoft Office</option> <option value="McAFree">McAFree Security</option> <option value="Adobe">Adobe CS6</option> <option value="Blizzard">Diablo 3</option> <option value="Activision">Call of Duty - Mordern Warfare</option> </select> </p> </div> <b>Comments</b> <br /><textarea name="description" rows="10" cols="40" onfocus="clearTextArea()">Pls write additional comment about your custom designed gaming computer</textarea> <p> <input type="button" class="buttonStyle" value="Place Order" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="placeOrder()" /> <input type="button" class="buttonStyle" value="Go Back" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="goBack()" /> </p> </form> </div> <div id="customerReport" style="display:none"> <p id="customerInfo"></p> <p><input type="button" class="buttonStyle" value="Return to Customer Form" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="returnToCustomer()" /></p> <table id="customerTable" border="1"> <tr> <thead class="theadStyle"> <td>First Name</td> <td>Last Name</td> <td>Email</td> <td>Password</td> <td>Zip</td> <td>Order</td> </thead> </tr> </table> </div> <div id="computerReport" style="display:none"> <p id="computerInfo"></p> <p><input type="button" class="buttonStyle" value="Return to Order Report" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="returnToReport()" /></p> <table id="computerTable" border="1"> <tr> <thead> <td>Processor</td> <td>Memory</td> <td>Graphics Card</td> <td>Power</td> <td>Software</td> </thead> </tr> </table> </div> </div> </div> <br class="clear" /> </div> </div> <div id="footer"> <div class="wrapper"> <div class="footbox"> <h2>About</h2> <ul> <li><a href="#">CloudCom</a></li> <li><a href="#">Events</a></li> <li><a href="#">Announcements</a></li> <li><a href="#">Blogs</a></li> <li class="last"><a href="#">Contacts</a></li> </ul> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Premium Support</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Forums</a></li> <li><a href="#">Discussion</a></li> <li class="last"><a href="#">Support</a></li> </ul> </div> <div class="footbox"> <h2>Developers</h2> <ul> <li><a href="#">Java</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li class="last"><a href="#">.Net</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Case Studies</a></li> <li><a href="#">Whitepapers</a></li> <li><a href="#">Seminars</a></li> <li><a href="#">Tutorials</a></li> <li class="last"><a href="#">Webminars</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 2012 - All Rights Reserved - <a href="#">www.cloudcom.com</a></p> <p class="fl_right"><a href="#">Reference OS Template</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
cloudcom.php
PHP
gpl3
14,949
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php if(isset($_SESSION["customerID"])){ require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here echo "Welcome customer ".$_SESSION["firstName"]." ".$_SESSION["lastName"]; ?> <p>Enter your card information:</p> <form method="post" name="payment" action="summary.php"> <p>Card number: <input type="text" class="rightAlign" name="cardNum" maxlength="16"/></p> <p>Name on card: <input type="text" class="rightAlign" name="cardName" maxlength="20"/></p> <p>Expiration date: <select name="expMonth"> <option value="01">01</option> <option value="02">02</option> <option value="03">03</option> <option value="04">04</option> <option value="05">05</option> <option value="06">06</option> <option value="07">07</option> <option value="08">08</option> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> <select name="expYear"> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> </p> <input type="submit" class="buttonStyle" value="Add Card" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php if(isset($_SESSION["customerID"])){ ?> <form method="post" name="logout" action="logout.php"> <input type="submit" value="Logout" class="logoutStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; }else{ require "customerLogin.html"; } ?> </body> </html>
zzspring2012csci571
payment.php
PHP
gpl3
2,739
<?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $productID =$_GET["productID"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); mysql_query("delete from products where productID = $productID"); mysql_close($con); echo "$productID"; }else{ require 'login.html'; } ?>
zzspring2012csci571
deleteProduct.php
PHP
gpl3
661
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here $email = $_POST["email"]; $password = $_POST["password"]; $displayLoginPage = true; if(strlen($email) == 0 || strlen($password) == 0){ $errorMsg = "Invalid customer login"; } if(strlen($email) == 0 && strlen($password) == 0){ $errorMsg = ""; } if(strlen($email) > 0 && strlen($password) > 0){ $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_errno()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from customers where email = '$email' and password = '$password'"); if(!($row = mysql_fetch_assoc($result))){ $errorMsg = "Invalid login"; }else{ $displayLoginPage = false; } } if($displayLoginPage){ require 'customerLogin.html'; }else{ mysql_query("update shoppingCarts set sessionID='".$row["customerID"]."' where sessionID='".session_id()."'"); mysql_query("delete from shoppingCarts where sessionID=".session_id()); $_SESSION["customerID"] = $row["customerID"]; $_SESSION["firstName"] = $row["firstName"]; $_SESSION["lastName"] = $row["lastName"]; require 'customer.php'; } mysql_close($con); ?> </body> </html>
zzspring2012csci571
customerLogin.php
PHP
gpl3
1,893
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "manager")){ $productName = $_GET["productName"]; $categoryID = $_GET["categoryID"]; $minPrice = $_GET["minPrice"]; $maxPrice = $_GET["maxPrice"]; $startDate = $_GET["startDate"]; $endDate = $_GET["endDate"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); $sql = "select sales.* from products, sales where products.productID=sales.productID"; // SELECT sales.* FROM products, sales where products.productID=sales.productID and products.productName='vm1' if(strlen($productName) != 0){ $sql = $sql." and products.productName='$productName'"; } if(strlen($categoryID) != 0){ $sql = $sql." and products.categoryID=$categoryID"; } if(strlen($minPrice) != 0){ $sql = $sql." and products.productPrice>=$minPrice"; } if(strlen($maxPrice) != 0){ $sql = $sql." and products.productPrice<=$maxPrice"; } // SELECT * FROM `sales` WHERE startDate>'2012-9-1' if(strlen($startDate) != 0){ $sql = $sql." sales.startDate>='$startDate'"; } if(strlen($endDate) != 0){ $sql = $sql." sales.endDate<='$endDate'"; } $result = mysql_query($sql); echo "query: $sql"; echo "<table border='1' id='saleTable'> <tr> <th>ProductID</th> <th>Discount</th> <th>Start Date</th> <th>End Date</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["productID"]."</td>"; echo "<td>".$row["discount"]."</td>"; echo "<td>".$row["startDate"]."</td>"; echo "<td>".$row["endDate"]."</td>"; echo "</tr>"; } echo "</table>"; }else{ require 'login.html'; } ?>
zzspring2012csci571
showSale.php
PHP
gpl3
2,111
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="styles/layout.css" type="text/css" /> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li><a href="index.html">Home</a></li> <li><a href="customerLogin.html">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a> </li> <li class="active"><a href="login.html">Employees</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="breadcrumb"> <div class="wrapper"> <p style="color:red" id="errorMsg">The field with label * is required</p> </div> </div> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <form method="post" name="customerLogin" action="customerLogin.php"> <p> <span class="redStar">*</span>Email: <input type="text" class="rightAlign" name="email" maxlength="40"/> </p> <p> <span class="redStar">*</span>Password: <input type="password" class="rightAlign" name="password" maxlength="20"/> </p> <input type="submit" class="buttonStyle" value="Login" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <a href="cloudcom.php">New customer please register here</a> </div> </div> <br class="clear" /> </div> </div> <div id="footer"> <div class="wrapper"> <div class="footbox"> <h2>About</h2> <ul> <li><a href="#">CloudCom</a></li> <li><a href="#">Events</a></li> <li><a href="#">Announcements</a></li> <li><a href="#">Blogs</a></li> <li class="last"><a href="#">Contacts</a></li> </ul> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Premium Support</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Forums</a></li> <li><a href="#">Discussion</a></li> <li class="last"><a href="#">Support</a></li> </ul> </div> <div class="footbox"> <h2>Developers</h2> <ul> <li><a href="#">Java</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li class="last"><a href="#">.Net</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Case Studies</a></li> <li><a href="#">Whitepapers</a></li> <li><a href="#">Seminars</a></li> <li><a href="#">Tutorials</a></li> <li class="last"><a href="#">Webminars</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 2012 - All Rights Reserved - <a href="#">www.cloudcom.com</a></p> <p class="fl_right"><a href="#">Reference OS Template</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
customerLogin.html
HTML
gpl3
3,842
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> <script type="text/javascript"> var xmlhttp; var productID; var categoryID; var saleID; var i, j, k; function deleteProduct(){ var productIDRB = document.sellerProduct.productID; for(i = 0; i < productIDRB.length; i++){ if(productIDRB[i].checked){ productID = productIDRB[i].value; break; } } if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyProduct; xmlhttp.open("GET", "deleteProduct.php?productID="+productID, true); xmlhttp.send(); } function handleReplyProduct(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); productTable = document.getElementById("productTable"); productTable.deleteRow(i+1); } } function deleteCategory(){ var categoryIDRB = document.sellerCategory.categoryID; for(j = 0; j < categoryIDRB.length; j++){ if(categoryIDRB[j].checked){ categoryID = categoryIDRB[j].value; break; } } if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplyCategory; xmlhttp.open("GET", "deleteCategory.php?categoryID="+categoryID, true); xmlhttp.send(); } function handleReplyCategory(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); categoryTable = document.getElementById("categoryTable"); categoryTable.deleteRow(j+1); } } function deleteSale(){ var saleIDRB = document.sellerSale.saleID; for(k = 0; k < saleIDRB.length; k++){ if(saleIDRB[k].checked){ saleID = saleIDRB[k].value; break; } } if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReplySale; xmlhttp.open("GET", "deleteSale.php?saleID="+saleID, true); xmlhttp.send(); } function handleReplySale(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); saleTable = document.getElementById("saleTable"); saleTable.deleteRow(k+1); } } </script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; echo "<br/>Welcome ".$_COOKIE["username"]; // put your code here $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from products"); echo "<h3>Product Table</h3>"; echo "<form method='post' name='sellerProduct' action='updateProduct.php'>"; echo "<table border='1' id='productTable'> <tr> <th>CategoryID</th> <th>Product name</th> <th>Product description</th> <th>Product image</th> <th>Product price</th> <th>Select</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td>".$row["productImage"]."</td>"; echo "<td>".$row["productPrice"]."</td>"; echo "<td><input type='radio' name='productID' value='".$row["productID"]."'/></td>"; echo "</tr>"; } echo "</table>"; echo "<input type='submit' value='Add or Change Product' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)'/>"; echo "<input type='button' value='Delete Product' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)' onclick='deleteProduct()'/>"; echo "</form><br/><br/>"; $result = mysql_query("select * from categories"); echo "<h3>Category Table</h3>"; echo "<form method='post' name='sellerCategory' action='updateCategory.php'>"; echo "<table border='1' id='categoryTable'> <tr> <th>CategoryID</th> <th>Category name</th> <th>Category description</th> <th>Select</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["categoryName"]."</td>"; echo "<td>".$row["categoryDescription"]."</td>"; echo "<td><input type='radio' name='categoryID' value='".$row["categoryID"]."'/></td>"; echo "</tr>"; } echo "</table>"; echo "<input type='submit' value='Add or Change Category' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)'/>"; echo "<input type='button' value='Delete Category' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)' onclick='deleteCategory()'/>"; echo "</form><br/><br/>"; $result = mysql_query("select * from sales"); echo "<h3>Sale Table</h3>"; echo "<form method='post' name='sellerSale' action='updateSale.php'>"; echo "<table border='1' id='saleTable'> <tr> <th>ProductID</th> <th>Discount</th> <th>Start Date</th> <th>End Date</th> <th>Select</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["productID"]."</td>"; echo "<td>".$row["discount"]."</td>"; echo "<td>".$row["startDate"]."</td>"; echo "<td>".$row["endDate"]."</td>"; echo "<td><input type='radio' name='saleID' value='".$row["saleID"]."'/></td>"; echo "</tr>"; } echo "</table>"; echo "<input type='submit' value='Add or Change Sale' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)'/>"; echo "<input type='button' value='Delete Sale' class='buttonStyle' onmouseover='changeOn(this)' onmouseout='changeOff(this)' onclick='deleteSale()'/>"; echo "</form>"; mysql_close($con); }else{ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
seller.php
PHP
gpl3
9,171
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $button = $_POST["button"]; $productID = $_POST["productID"]; $categoryID = $_POST["categoryID"]; $productName = $_POST["productName"]; $productDescription = $_POST["productDescription"]; $productImage = $_FILES["productImage"]["name"]; $productPrice = $_POST["productPrice"]; if(strcmp($button, "Cancel")){ $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); if(strlen($productID) == 0){ mysql_query("insert into products values (null, '$categoryID', '$productName', '$productDescription', '$productImage', $productPrice)"); // echo "<p style='color:red'>new product $productName is inserted</p>"; }else{ mysql_query("update products set categoryID='$categoryID', productName='$productName', productDescription='$productDescription', productImage='$productImage', productPrice=$productPrice where productID=$productID"); // echo "<p style='color:red'>product $productID is updated</p>"; } mysql_close($con); if(($_FILES["productImage"]["type"] == "image/gif" || $_FILES["productImage"]["type"] == "image/jpeg" || $_FILES["productImage"]["type"] == "image/pjpeg") || $_FILES["productImage"]["type"] == "image/png" && ($_FILES["productImage"]["size"]) <= 100000){ if($_FILES["productImage"]["error"] > 0){ echo "error: ".$_FILES["productImage"]["error"]."<br/>"; }else{ // echo "uploaded: ".$_FILES["productImage"]["name"]."<br/>"; // echo "type: ".$_FILES["productImage"]["type"]."<br/>"; // echo "size: ".($_FILES["productImage"]["size"]/1024)." Kb<br/>"; // echo "store: ".$_FILES["productImage"]["tmp_name"]; if(file_exists("images/products/".$_FILES["productImage"]["name"])){ // echo $_FILES["productImage"]["name"]." already exist"; }else{ move_uploaded_file($_FILES["productImage"]["tmp_name"], "images/products/".$_FILES["productImage"]["name"]); } } }else{ echo "invalid file"; } require 'seller.php'; }else{ require 'seller.php'; } }else{ require 'login.html'; } ?> </body> </html>
zzspring2012csci571
commitProduct.php
PHP
gpl3
3,198
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "administrator")){ $userID =$_GET["userID"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); mysql_query("delete from users where userID = $userID"); mysql_close($con); echo "$userID"; }else{ require 'login.html'; } ?>
zzspring2012csci571
deleteUser.php
PHP
gpl3
684
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> <script type="text/javascript"> var xmlhttp; var cartID; var i; function deleteItem(){ var cartIDRB = document.shoppingCart.cartID; for(i = 0; i < cartIDRB.length; i++){ if(cartIDRB[i].checked){ cartID = cartIDRB[i].value; alert(cartID); break; } } if(window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, and Safari xmlhttp = new XMLHttpRequest(); }else{ //code for IE6 and IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = handleReply; xmlhttp.open("GET", "deleteItem.php?cartID="+cartID, true); xmlhttp.send(); } function handleReply(){ if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ // alert(xmlhttp.responseText); userTable = document.getElementById("cartTable"); userTable.deleteRow(i+1); } } </script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here echo "Welcome customer ".$_SESSION["firstName"]." ".$_SESSION["lastName"]; // echo session_id(); $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); /*For up to 5 points extra credit, keep track of what items are purchased together - like what Amazon does. When a customer puts an item in their shopping cart, display item(s) that other customers also bought in a single order.*/ if(isset($_SESSION["customerID"])){ $result = mysql_query("select * from shoppingCarts S, products P where S.productID = P.productID and S.sessionID='".$_SESSION["customerID"]."'"); $result1 = mysql_query("select * from products P where P.categoryID in (select P.categoryID from shoppingCarts S, products P where S.productID=P.productID and S.sessionID=".$_SESSION["customerID"].")"); }else{ $result = mysql_query("select * from shoppingCarts S, products P where S.productID = P.productID and S.sessionID='".session_id()."'"); $result1 = mysql_query("select * from products P where P.categoryID in (select P.categoryID from shoppingCarts S, products P where S.productID=P.productID and S.sessionID=".session_id().")"); } ?> <form method="post" name="shoppingCart" action="payment.php"> <table border="1" id="cartTable"> <tr> <th>Product Name</th> <th>Product Description</th> <th>Product Image</th> <th>Product Price</th> <th>Product Quantity</th> <th>Select</th> </tr> <?php while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td><img src='images/products/".$row["productImage"]."' width='100' height='100' alt='image' /></td>"; echo "<td>".$row["productPrice"]."</td>"; echo "<td>".$row["productQuantity"]."</td>"; echo "<td><input type='radio' name='cartID' value='".$row["cartID"]."'/></td>"; echo "</tr>"; } mysql_close($con); ?> </table> <input type="submit" value="Checkout" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="button" value="Delete Item" class="buttonStyle" onclick="deleteItem()" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <form method="post" name="customer" action="updateCart.php"> <p>Other customer also order the following items</p> <table border="1" id="productTable"> <tr> <th>Category ID</th> <th>Product name</th> <th>Product description</th> <th>Product image</th> <th>Product price</th> <th>Select</th> </tr> <?php while($row1 = mysql_fetch_assoc($result1)){ echo "<tr>"; echo "<td>".$row1["categoryID"]."</td>"; echo "<td>".$row1["productName"]."</td>"; echo "<td>".$row1["productDescription"]."</td>"; echo "<td><img src='images/products/".$row1["productImage"]."' width='100' heigth='100' alt='image' /></td>"; echo "<td>".$row1["productPrice"]."</td>"; echo "<td><input type='radio' name='productID' value='".$row1["productID"]."'/></td>"; echo "</tr>"; } ?> </table> <select name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5+</option> </select> <input type="submit" value="Add to Cart" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php if(isset($_SESSION["customerID"])){ ?> <form method="post" name="logout" action="logout.php"> <input type="submit" value="Logout" class="logoutStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
showCart.php
PHP
gpl3
7,239
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here $productID = $_POST["productID"]; $productQuantity = $_POST["quantity"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); if(isset($_SESSION["customerID"])){ mysql_query("insert into shoppingCarts values (null, $productID, $productQuantity, '".$_SESSION["customerID"]."')"); }else{ mysql_query("insert into shoppingCarts values (null, $productID, $productQuantity, '".session_id()."')"); } mysql_close($con); echo "new product $productID is inserted"; require 'showCart.php'; ?> </body> </html>
zzspring2012csci571
updateCart.php
PHP
gpl3
1,109
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here echo "Welcome customer ".$_SESSION["firstName"]." ".$_SESSION["lastName"]; // echo session_id(); $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from orders where customerID = ".$_SESSION["customerID"]); ?> <form method="post" name="order" action="showItem.php"> <table border="1" id="orderTable"> <tr> <th>Order date</th> <th>Total price</th> <th>Credit card number</th> <th>Credit card name</th> <th>Credit card expiration date</th> <th>Select</th> </tr> <?php while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["orderDate"]."</td>"; echo "<td>".$row["totalPrice"]."</td>"; echo "<td>".$row["cardNum"]."</td>"; echo "<td>".$row["cardName"]."</td>"; echo "<td>".$row["expDate"]."</td>"; echo "<td><input type='radio' name='orderID' value='".$row["orderID"]."'/></td>"; } mysql_close($con); ?> </table> <input type="submit" value="Order Detail" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php if(isset($_SESSION["customerID"])){ ?> <form method="post" name="logout" action="logout.php"> <input type="submit" value="Logout" class="logoutStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
showOrder.php
PHP
gpl3
2,724
<?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <body> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $saleID = $_POST["saleID"]; if(strlen($saleID) == 0){ //add a new product echo "<h2>Add a new sale</h2>"; }else{ echo "<h2>Change selected sale</h2>"; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from sales where saleID = $saleID"); $row = mysql_fetch_assoc($result); mysql_close($con); } ?> <form method="post" action="commitSale.php"> <input type="text" name="saleID" style="display: none" <?php if(strlen($saleID) != 0){ echo "value='".$saleID."'"; } ?> /> <p>Product ID: <input type="text" name="productID" maxlength="20" class="rightAlign" <?php if(strlen($saleID) != 0){ echo "value='".$row["productID"]."'"; } ?> /></p> <p>Discount: <input type="text" name="discount" maxlength="20" class="rightAlign" <?php if(strlen($saleID) != 0){ echo "value='".$row["discount"]."'"; } ?> /></p> <p>Start date: <input type="text" name="startDate" maxlength="20" class="rightAlign" <?php if(strlen($saleID) != 0){ echo "value='".$row["startDate"]."'"; } ?> /></p> <p>End date: <input type="text" name="endDate" maxlength="20" class="rightAlign" <?php if(strlen($saleID) != 0){ echo "value='".$row["endDate"]."'"; } ?> /><p> <input type="submit" name="button" value="Commit sale" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="submit" name="button" value="Cancel" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php }else{ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
updateSale.php
PHP
gpl3
3,753
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "administrator")){ $userID = $_POST["userID"]; if(strlen($userID) == 0){ //add a new user echo "<h2>Add a new user</h2>"; }else{ echo "<h2>Change selected user</h2>"; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from users where userID = $userID"); $row = mysql_fetch_assoc($result); mysql_close($con); } ?> <form method="post" action="commitUser.php"> <input type="text" name="userID" style="display: none" <?php if(strlen($userID) != 0){ echo "value='".$userID."'"; } ?> /> <p>Username: <input type="text" name="username" maxlength="20" class="rightAlign" <?php if(strlen($userID) != 0){ echo "value='".$row["username"]."'"; } ?> /></p> <p>Password: <input type="password" name="password" maxlength="20" class="rightAlign" <?php if(strlen($userID) != 0){ echo "value='".$row["password"]."'"; } ?> /></p> <p>First name: <input type="text" name="firstName" maxlength="20" class="rightAlign" <?php if(strlen($userID) != 0){ echo "value='".$row["firstName"]."'"; } ?> /></p> <p>Last name: <input type="text" name="lastName" maxlength="20" class="rightAlign" <?php if(strlen($userID) != 0){ echo "value='".$row["lastName"]."'"; } ?> /></p> <p>DoB: <input type="text" name="dob" class="rightAlign" <?php if(strlen($userID) != 0){ echo "value='".$row["dob"]."'"; } ?> /></p> User type:<br/> <input type="radio" name="userType" value="administrator" <?php if(strlen($userID) != 0 && !strcmp($row["userType"], "administrator")){ echo "checked"; }?> />Administrator<br/> <input type="radio" name="userType" value="manager" <?php if(strlen($userID) != 0 && !strcmp($row["userType"], "manager")){ echo "checked"; }?> />Manager<br/> <input type="radio" name="userType" value="seller" <?php if(strlen($userID) != 0 && !strcmp($row["userType"], "seller")){ echo "checked"; }?> />Seller<br/> <input type="submit" name="button" value="Commit user" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="submit" name="button" value="Cancel" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php }else{ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
updateUser.php
PHP
gpl3
5,045
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; //put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "manager")){ $productName = $_GET["productName"]; $categoryID = $_GET["categoryID"]; $minPrice = $_GET["minPrice"]; $maxPrice = $_GET["maxPrice"]; $flag = 0; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); $sql = "select * from products"; if(strlen($productName) != 0){ if($flag == 0){ $sql = $sql." where productName='$productName'"; $flag = 1; }else{ $sql = $sql." and productName='$productName'"; } } if(strlen($categoryID) != 0){ if($flag == 0){ $sql = $sql." where categoryID=$categoryID"; $flag = 1; }else{ $sql = $sql." and categoryID=$categoryID"; } } if(strlen($minPrice) != 0){ if($flag == 0){ $sql = $sql." where productPrice>=$minPrice"; $flag = 1; }else{ $sql = $sql." and productPrice>=$minPrice"; } } if(strlen($maxPrice) != 0){ if($flag == 0){ $sql = $sql." where productPrice<=$maxPrice"; $flag = 1; }else{ $sql = $sql." and productPrice<=$maxPrice"; } } echo "query: $sql"; $result = mysql_query($sql); echo "<table border='1' id='productTable'> <tr> <th>CategoryID</th> <th>Product name</th> <th>Product description</th> <th>Product image</th> <th>Product price</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td>".$row["productImage"]."</td>"; echo "<td>".$row["productPrice"]."</td>"; echo "</tr>"; } echo "</table>"; mysql_close($con); }else{ require 'login.html'; } ?>
zzspring2012csci571
showProduct.php
PHP
gpl3
2,332
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head> <title>CloudCom</title> <link rel="stylesheet" href="styles/layout.css" type="text/css" /> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body id="top"> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li><a href="index.html">Home</a></li> <li><a href="customerLogin.html">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a> </li> <li class="active"><a href="login.html">Employees</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="breadcrumb"> <div class="wrapper"> <p style="color:red" id="errorMsg">The field with label * is required</p> </div> </div> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <form method="post" name="login" action="login.php"> <p><span class="redStar">*</span>Username: <input type="text" class="rightAlign" name="username" maxlength="20"/></p> <p><span class="redStar">*</span>Password: <input type="password" class="rightAlign" name="password" maxlength="20"/></p> <input type="submit" class="buttonStyle" value="Login" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form><br/> <a href='http://localhost:8888/cloudcom/register.html'>New employee please register here</a> <div id="customerReport" style="display:none"> <p id="customerInfo"></p> <p><input type="button" class="buttonStyle" value="Return to Customer Form" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="returnToCustomer()" /></p> <table id="customerTable" border="1"> <tr> <thead class="theadStyle"> <td>First Name</td> <td>Last Name</td> <td>Email</td> <td>Password</td> <td>Zip</td> <td>Order</td> </thead> </tr> </table> </div> <div id="computerReport" style="display:none"> <p id="computerInfo"></p> <p><input type="button" class="buttonStyle" value="Return to Order Report" onmouseover="changeOn(this)" onmouseout="changeOff(this)" onclick="returnToReport()" /></p> <table id="computerTable" border="1"> <tr> <thead> <td>Processor</td> <td>Memory</td> <td>Graphics Card</td> <td>Power</td> <td>Software</td> </thead> </tr> </table> </div> </div> </div> <br class="clear" /> </div> </div> <div id="footer"> <div class="wrapper"> <div class="footbox"> <h2>About</h2> <ul> <li><a href="#">CloudCom</a></li> <li><a href="#">Events</a></li> <li><a href="#">Announcements</a></li> <li><a href="#">Blogs</a></li> <li class="last"><a href="#">Contacts</a></li> </ul> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Premium Support</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Forums</a></li> <li><a href="#">Discussion</a></li> <li class="last"><a href="#">Support</a></li> </ul> </div> <div class="footbox"> <h2>Developers</h2> <ul> <li><a href="#">Java</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li class="last"><a href="#">.Net</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Case Studies</a></li> <li><a href="#">Whitepapers</a></li> <li><a href="#">Seminars</a></li> <li><a href="#">Tutorials</a></li> <li class="last"><a href="#">Webminars</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 2012 - All Rights Reserved - <a href="#">www.cloudcom.com</a></p> <p class="fl_right"><a href="#">Reference OS Template</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
login.html
HTML
gpl3
4,731
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ session_start(); $category = $_GET["category"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); if($category != 0){ $result1 = mysql_query("select * from products where categoryID=".$category); $result2 = mysql_query("select * from products P, sales S where P.productID=S.productID and P.categoryID = ".$category); }else{ $result1 = mysql_query("select * from products"); $result2 = mysql_query("select * from products P, sales S where P.productID=S.productID"); } echo "<table border='1' id='productTable'>"; echo "<tr><th>Category ID</th><th>Product name</th><th>Product description</th><th>Product image</th><th>Product price</th><th>Select</th></tr>"; while($row = mysql_fetch_assoc($result1)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td>".$row["productDescription"]."</td>"; echo "<td><img src='images/products/".$row["productImage"]."' width='100' heigth='100' alt='image' /></td>"; echo "<td>".$row["productPrice"]."</td>"; echo "<td><input type='radio' name='productID' value='".$row["productID"]."'/></td>"; echo "</tr>"; } mysql_close($con); echo "</table>"; echo "<table border='1' id='saleTable'>"; echo "<tr><th>Category ID</th> <th>Product name</th> <th>Sale image</th> <th>Discount</th> <th>Start date</th> <th>End date</th></tr>"; while($row = mysql_fetch_assoc($result2)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["productName"]."</td>"; echo "<td><img src='images/products/sale.jpg' width='100' heigth='100' alt='image' /></td>"; echo "<td>".$row["discount"]."</td>"; echo "<td>".$row["startDate"]."</td>"; echo "<td>".$row["endDate"]."</td>"; echo "</tr>"; } echo "</table>"; ?>
zzspring2012csci571
changeCategory.php
PHP
gpl3
2,257
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "manager")){ $userType = $_GET["userType"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); $sql = "select * from users"; if(!strcmp($userType, "administrator")){ $sql = $sql." where userType='$userType'"; }else if(!strcmp($userType, "seller")){ $sql = $sql." where userType='$userType'"; }else if(!strcmp($userType, "manager")){ $sql = $sql." where userType='$userType'"; } $result = mysql_query($sql); echo "query: $sql"; echo "<table border='1' id='userTable'> <tr> <th>Username</th> <th>Password</th> <th>First name</th> <th>Last name</th> <th>DOB</th> <th>User type</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["username"]."</td>"; echo "<td>".$row["password"]."</td>"; echo "<td>".$row["firstName"]."</td>"; echo "<td>".$row["lastName"]."</td>"; echo "<td>".$row["dob"]."</td>"; echo "<td>".$row["userType"]."</td>"; echo "</tr>"; } echo "</table>"; }else{ require 'login.html'; } ?>
zzspring2012csci571
showUser.php
PHP
gpl3
1,572
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $button = $_POST["button"]; $categoryID = $_POST["categoryID"]; $categoryName = $_POST["categoryName"]; $categoryDescription = $_POST["categoryDescription"]; if(strcmp($button, "Cancel")){ $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); $result = mysql_query("select * from categories where categoryID = $categoryID"); if(!mysql_fetch_array($result)){ mysql_query("insert into categories values ('$categoryID', '$categoryName', '$categoryDescription')"); // echo "new category $categoryName is inserted"; }else{ mysql_query("update categories set categoryName='$categoryName', categoryDescription='$categoryDescription' where categoryID=$categoryID"); // echo "record $categoryName is updated"; } mysql_close($con); require 'seller.php'; }else{ require 'seller.php'; } }else{ require 'login.html'; } ?> </body> </html>
zzspring2012csci571
commitCategory.php
PHP
gpl3
1,743
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ session_start(); /* try { $dbh = new PDO("mysql:host=localhost;dbname=cloudcom", "zhouzhao", "19831022"); //begin a trasaction and turn off auto-commit $dbh->beginTransaction(); $sql = "insert into orders values(null, ".$_SESSION["customerID"].", '".date("Y-m-d")."', ".$_SESSION["totalPrice"].", '".$_SESSION["cardNum"]."', '".$_SESSION["cardName"]."', '".$_SESSION["expDate"]."')"; // echo $sql; $dbh->exec($sql); $orderID = $dbh->lastInsertId(); foreach ($dbh->query("select * from shoppingCarts S, products P where S.productID=P.productID and S.sessionID=".$_SESSION["customerID"]) as $row) { $sql = "insert into items values(null, $orderID, ".$row["productID"].", ".$row["productQuantity"].", ".$row["productPrice"].")"; // echo $sql; $dbh->exec($sql); } $dbh->exec("delete from shoppingCarts where sessionID=".$_SESSION["customerID"]); //commit the changes $dbh->commit(); $dbh = NULL; require 'showOrder.php'; } catch (PDOException $exc) { echo "error: ".$exc->getMessage()."<br/>"; die(); } */ $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); mysql_query("insert into orders values(null, ".$_SESSION["customerID"].", '".date("Y-m-d")."', ".$_SESSION["totalPrice"].", '".$_SESSION["cardNum"]."', '".$_SESSION["cardName"]."', '".$_SESSION["expDate"]."')"); $orderID = mysql_fetch_assoc(mysql_query("select orderID from orders where customerID=".$_SESSION["customerID"]." and cardNum='".$_SESSION["cardNum"]."'")); $result = mysql_query("select * from shoppingCarts S, products P where S.productID=P.productID and S.sessionID=".$_SESSION["customerID"]); while ($row = mysql_fetch_assoc($result)) { mysql_query("insert into items values(null, ".$orderID["orderID"].", ".$row["productID"].", ".$row["productQuantity"].", ".$row["productPrice"].")"); } mysql_query("delete from shoppingCarts where sessionID=".$_SESSION["customerID"]); require "showOrder.php"; ?>
zzspring2012csci571
placeOrder.php
PHP
gpl3
2,418
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr"> <head profile="http://gmpg.org/xfn/11"> <title>Cloud Computing</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="imagetoolbar" content="no" /> <link rel="stylesheet" href="styles/layout.css" type="text/css" /> <script type="text/javascript" src="scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript" src="scripts/jquery.easing.1.3.js"></script> <script type="text/javascript" src="scripts/jquery.hoverIntent.js"></script> <script type="text/javascript" src="scripts/jquery.hslides.1.0.js"></script> <script type="text/javascript" src="scripts/jquery.hslides.setup.js"></script> </head> <body id="top"> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li class="active"><a href="index.html">Home</a></li> <li><a href="customerLogin.html">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a></li> <li><a href="login.html" class="last">Employees</a></li> </ul> </div> <div id="search"> <form action="#" method="post"> <fieldset> <legend>Site Search</legend> <input type="text" value="Search Our Website&hellip;" onfocus="this.value=(this.value=='Search Our Website&hellip;')? '' : this.value ;" /> <input type="submit" name="go" id="go" value="Search" /> </fieldset> </form> </div> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="featured_slide"> <div class="wrapper"> <div class="featured_content"> <ul id="accordion"> <li class="current"> <div class="featured_box"> <h2>1. Central Processing Unit</h2> <p> The CPU is the hardware within a computer system which executes computer instructions by performing arithmetic, logic, and I/O operations. With our CPU virtualization technology, multiple VM can share one physical CPU to improve utilization rate. With multi-core virtualization technology, one VM can have multi-core virtual CPU. </p> <p class="readmore"><a href="http://en.wikipedia.org/wiki/Central_processing_unit">More &raquo;</a></p> </div> <div class="featured_tab"> <img src="images/New_Core_I7.jpg" alt="cpu" width="100" height="100"/> <p>CPU<br />Technology</p> </div> </li> <li> <div class="featured_box"> <h2>2. Graphics Processing Unit</h2> <p> A GPU is a intergrated circuit designed to accelerate processing of 2D/3D images on computer display. With our general purpose parallel computing architecture in GPU, more applications in the field of finance, biology, and database etc. can be accelerated. We have strong relationship with GPU computing community to advance future GPU supercomputing. </p> <p class="readmore"><a href="http://en.wikipedia.org/wiki/Graphics_processing_unit">More &raquo;</a></p> </div> <div class="featured_tab"><img src="images/demo/nvidia_GPU.jpg" alt="gpu" width="100" height="100"/> <p>GPU<br />Technology</p> </div> </li> <li> <div class="featured_box"> <h2>3. Memory</h2> <p> Memory refers to the physical devices used to store computer programs and data for CPU computing. Our database system transform from disk storage into main memory computing storage. The in-memory database is optmized with algorithms for efficient query. Our in-memory database technology is widely used in telecommunciation and mobile network. </p> <p class="readmore"><a href="http://en.wikipedia.org/wiki/Computer_memory">More &raquo;</a></p> </div> <div class="featured_tab"><img src="images/demo/memory.jpg" alt="memory" width="100" height="100"/> <p>Memory Technology</p> </div> </li> <li> <div class="featured_box"> <h2>4. Solid-state drive</h2> <p> Solid-state drive is a data storage devices that use integrated circuits assembled to memory. SSD do not employ any moving mechanical devices, which is different from hard disk drives. Therefore, the data read/write latency is much faster than traditional storage. </p> <p class="readmore"><a href="#">More &raquo;</a></p> </div> <div class="featured_tab"><img src="images/demo/ssd.jpg" alt="ssd" width="100" height="100"/> <p>Storage Technology</p> </div> </li> <li> <div class="featured_box"> <h2>5. Nullain convallis ris elis</h2> <p>Nullamcorpervivamus nisl in sed adipit donec feugiat lor vel velit volutpat. Wisihabitur diculisi ac curabitur cursuspendreris sociis sed eger ipsum condisse laculis. Curabiturid non eu curabitae nibh por nullamcorper at nibh elis fring. Vestnibh congue praesenenatis justo et maecenasceleifend senterdum malesuada at dolor amet. Turisristibulum curabitae eros leo at interd.</p> <p class="readmore"><a href="#">More &raquo;</a></p> </div> <div class="featured_tab"><img src="images/demo/router.jpg" alt="router" width="100" height="100"/> <p>Network Technology</p> </div> </li> </ul> </div> </div> </div> <!-- ####################################################################################################### --> <div id="homecontent"> <div class="wrapper"> <ul> <li> <h2 class="title"><img src="images/demo/alien1.jpg" alt="alien1" width="60" height="60"/>Small VM Instance</h2> <p> Small Instance (Default) 1.7 GB of memory, 1 EC2 Compute Unit (1 virtual core with 1 EC2 Compute Unit), 160 GB of local instance storage, 32-bit or 64-bit platform. </p> <p class="readmore"><a href="#">More &raquo;</a></p> </li> <li> <h2 class="title"><img src="images/demo/alien2.jpg" alt="alien2" width="60" height="60"/>Mediate VM Instance</h2> <p> Medium Instance 3.75 GB of memory, 2 EC2 Compute Units (1 virtual core with 2 EC2 Compute Units each), 410 GB of local instance storage, 32-bit or 64-bit platform. </p> <p class="readmore"><a href="#">More &raquo;</a></p> </li> <li class="last"> <h2 class="title"><img src="images/demo/alien3.jpg" alt="alien3" width="60" height="60"/>Large VM Instance</h2> <p> Large Instance 7.5 GB of memory, 4 EC2 Compute Units (2 virtual cores with 2 EC2 Compute Units each), 850 GB of local instance storage, 64-bit platform </p> <p class="readmore"><a href="#">More &raquo;</a></p> </li> </ul> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="container"> <div class="wrapper"> <div id="content"> <h2>About Our Company</h2> <p>CloudCom is a web service company that provides elastic computing virtual machine (VM) in our datacenter. Our goal is to make web-scale computing accesible for any developers.</p> <p>CloudCom's simple web service interface ease the process of provisioning, monitoring VM instance. It also provides you complete control of your computing resources in our secured datacenter.</p> <p>CloudCom's technology in CPU, GPU, and memory help you quickly rent, boot, and scale up or down your VM based on your computing requirements</p> <p>The economics of computing is evoled to model of pay-as-you-go. CloudCom only charge you based on how much you use our service hour by hour.</p> <p>With new API for developers, more developers use CloudCom's services to host website and distribute applications to customers.</p> </div> <div id="column"> <div class="holder"> <h2>New Technology</h2> <ul id="latestnews"> <li> <img class="imgl" src="images/demo/windows-icon.jpg" alt="win8" width="100" height="75"/> <p><strong><a href="#">VM support Windows 7 OS</a></strong></p> <p>Receive 1000 hours per month of CloudCom Windows Server Instance.</p> </li> <li class="last"> <img class="imgl" src="images/demo/apple.jpg" alt="macosx" width="100" height="75"/> <p><strong><a href="#">VM support Mac OS X OS</a></strong></p> <p>VM now support Apple Mac OS X server.</p> </li> </ul> </div> </div> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="footer"> <div class="wrapper"> <div id="newsletter"> <h2>Let us serve you better!</h2> <p>Please enter your email to join our mailing list</p> <form action="#" method="post"> <fieldset> <legend>News Letter</legend> <input type="text" value="Enter Email Here&hellip;" onfocus="this.value=(this.value=='Enter Email Here&hellip;')? '' : this.value ;" /> <input type="submit" name="news_go" id="news_go" value="GO" /> </fieldset> </form> <p>To unsubscribe please <a href="#">click here &raquo;</a></p> </div> <div class="footbox"> <h2>Support</h2> <ul> <li><a href="#">Forums</a></li> <li><a href="#">FAQs</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Events</a></li> <li class="last"><a href="#">Press</a></li> </ul> </div> <div class="footbox"> <h2>Developer</h2> <ul> <li><a href="#">Cloud</a></li> <li><a href="#">Web</a></li> <li><a href="#">Mobile</a></li> <li><a href="#">Data mining</a></li> <li class="last"><a href="#">Business intelligence</a></li> </ul> </div> <div class="footbox"> <h2>Learn</h2> <ul> <li><a href="#">Services</a></li> <li><a href="#">Case studies</a></li> <li><a href="#">Economics</a></li> <li><a href="#">Papers</a></li> <li class="last"><a href="#">Tutorials</a></li> </ul> </div> <br class="clear" /> </div> </div> <!-- ####################################################################################################### --> <div id="copyright"> <div class="wrapper"> <p class="fl_left">Copyright &copy; 1983 - 2012 All Rights Reserved <a href="#">www.cloudcom.com</a></p> <p class="fl_right">Template by <a href="http://www.os-templates.com/" title="Free Website Templates">OS Templates</a></p> <br class="clear" /> </div> </div> </body> </html>
zzspring2012csci571
index.html
HTML
gpl3
11,707
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $email = $_POST["email"]; $password = $_POST["password"]; $homePhone = $_POST["homePhone1"].$_POST["homePhone2"].$_POST["homePhone3"]; $cellPhone = $_POST["cellPhone1"].$_POST["cellPhone2"].$_POST["cellPhone3"]; $street = $_POST["street"]; $city = $_POST["city"]; $state = $_POST["state"]; $zip = $_POST["zip"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); mysql_query("insert into customers values (null, '$firstName', '$lastName', '$email', '$password', '$homePhone', '$cellPhone', '$street', '$city', '$state', '$zip')"); mysql_close($con); require 'customerLogin.html'; ?> </body> </html>
zzspring2012csci571
customerRegister.php
PHP
gpl3
1,403
<?php session_start(); echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $categoryID = $_POST["categoryID"]; if(strlen($categoryID) == 0){ //add a new product echo "<h2>Add a new category</h2>"; }else{ echo "<h2>Change selected category</h2>"; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from categories where categoryID = $categoryID"); $row = mysql_fetch_assoc($result); mysql_close($con); } ?> <form method="post" action="commitCategory.php"> <p>Category ID: <input type="text" name="categoryID" maxlength="20" class="rightAlign" <?php if(strlen($categoryID) != 0){ echo "value='".$row["categoryID"]."'"; } ?> /></p> <p>Category Name: <input type="text" name="categoryName" maxlength="20" class="rightAlign" <?php if(strlen($categoryID) != 0){ echo "value='".$row["categoryName"]."'"; } ?> /></p> Category Description: <textarea rows="3" cols="22" name="categoryDescription" maxlength="50" > <?php if(strlen($categoryID) != 0){ echo $row["categoryDescription"]; } ?> </textarea><br/> <input type="submit" name="button" value="Commit category" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="submit" name="button" value="Cancel" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php }else{ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
updateCategory.php
PHP
gpl3
3,295
<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="header"> <div class="wrapper"> <div class="fl_left"> <h1><a href="#">CloudCom</a></h1> <p>Make the Earth Smarter</p> </div> <div class="fl_right"> <a href="#"><img src="images/demo/banner1.jpg" alt="cloudcom" width="468" height="70"/></a> </div> <br class="clear" /> </div> </div> <div id="topbar"> <div class="wrapper"> <div id="topnav"> <ul> <li><a href="index.html">Home</a></li> <li><a href="customerLogin.html">Customer</a></li> <li><a href="customer.php">Services</a></li> <li><a href="showCart.php">Cart</a> </li> <li class="active"><a href="login.html">Employees</a></li> </ul> </div> <br class="clear" /> </div> </div> <div id="breadcrumb"> <div class="wrapper"> <p style="color:red" id="errorMsg">The field with label * is required</p> </div> </div> </body> </html>
zzspring2012csci571
header.html
HTML
gpl3
1,195
<?php session_start(); ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <link rel="stylesheet" href="styles/layout.css" type="text/css"/> <link rel="stylesheet" href="styles/computer.css" type="text/css"/> <script type="text/javascript" src="scripts/computer.js"></script> </head> <body> <?php require 'header.html'; ?> <div id="container"> <div class="wrapper"> <div id="content"> <div id="order"> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; $productID = $_POST["productID"]; if(strlen($productID) == 0){ //add a new product echo "<h2>Add a new product</h2>"; }else{ echo "<h2>Change selected product</h2>"; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_select_db("cloudcom", $con); $result = mysql_query("select * from products where productID = $productID"); $row = mysql_fetch_assoc($result); mysql_close($con); } ?> <form method="post" action="commitProduct.php" enctype="multipart/form-data"> <input type="text" name="productID" style="display: none" <?php if(strlen($productID) != 0){ echo "value='".$productID."'"; } ?> /> <p>Category ID: <input type="text" name="categoryID" maxlength="20" class="rightAlign" <?php if(strlen($productID) != 0){ echo "value='".$row["categoryID"]."'"; } ?> /></p> <p>Product Name: <input type="text" name="productName" maxlength="20" class="rightAlign" <?php if(strlen($productID) != 0){ echo "value='".$row["productName"]."'"; } ?> /></p> Product Description: <textarea rows="3" cols="22" name="productDescription" maxlength="50"> <?php if(strlen($productID) != 0){ echo $row["productDescription"]; } ?> </textarea><br/> <p>Product Image: <input type="file" name="productImage" maxlength="50" class="rightAlign" <?php if(strlen($productID) != 0){ echo "value='".$row["productIamge"]."'"; } ?> /></p> <p>Product Price: <input type="text" name="productPrice" class="rightAlign" <?php if(strlen($productID) != 0){ echo "value='".$row["productPrice"]."'"; } ?> /></p> <input type="submit" name="button" value="Commit Product" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> <input type="submit" name="button" value="Cancel" class="buttonStyle" onmouseover="changeOn(this)" onmouseout="changeOff(this)"/> </form> <?php }else{ require 'login.html'; } ?> </div> </div> <br class="clear" /> </div> </div> <?php require 'tail.html'; ?> </body> </html>
zzspring2012csci571
updateProduct.php
PHP
gpl3
4,152
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "manager")){ $categoryName = $_GET["categoryName"]; $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); $sql = "select * from categories"; if(strlen($categoryName) != 0){ $sql = $sql." where categoryName='$categoryName'"; } $result = mysql_query($sql); echo "query: $sql"; echo "<table border='1' id='categoryTable'> <tr> <th>CategoryID</th> <th>Category name</th> <th>Category description</th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr>"; echo "<td>".$row["categoryID"]."</td>"; echo "<td>".$row["categoryName"]."</td>"; echo "<td>".$row["categoryDescription"]."</td>"; echo "</tr>"; } echo "</table>"; }else{ require 'login.html'; } ?>
zzspring2012csci571
showCategory.php
PHP
gpl3
1,240
<?php session_start(); // echo "Login: ".$_SESSION["userID"]." ".$_SESSION["userType"]; ?> <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <?php // put your code here if(isset($_SESSION["userID"]) && !strcmp($_SESSION["userType"], "seller")){ $button = $_POST["button"]; $saleID = $_POST["saleID"]; $productID = $_POST["productID"]; $discount = $_POST["discount"]; $startDate = $_POST["startDate"]; $endDate = $_POST["endDate"]; if(strcmp($button, "Cancel")){ $con = mysql_connect("localhost", "zhouzhao", "19831022"); if(!$con){ die("could not connect to DB: ".mysql_error()); } mysql_selectdb("cloudcom", $con); if(strlen($saleID) == 0){ mysql_query("insert into sales values (null, '$productID', $discount, '$startDate', '$endDate')"); // echo "<p style='color:red'>new sale $saleID is inserted</p>"; }else{ mysql_query("update sales set productID='$productID', discount=$discount, startDate='$startDate', endDate='$endDate' where saleID=$saleID"); // echo "<p style='color:red'>sale $saleID is updated</p>"; } mysql_close($con); require 'seller.php'; }else{ require 'seller.php'; } }else{ require 'login.html'; } ?> </body> </html>
zzspring2012csci571
commitSale.php
PHP
gpl3
1,716
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file target-subr.c * @brief Target-related subroutines. (ie. determine target type, print target, etc.) */ #include <inttypes.h> #include <nfc/nfc.h> #include "target-subr.h" struct card_atqa { uint16_t atqa; uint16_t mask; char type[128]; // list of up to 8 SAK values compatible with this ATQA int saklist[8]; }; struct card_sak { uint8_t sak; uint8_t mask; char type[128]; }; struct card_atqa const_ca[] = { { 0x0044, 0xffff, "MIFARE Ultralight", {0, -1} }, { 0x0044, 0xffff, "MIFARE Ultralight C", {0, -1} }, { 0x0004, 0xff0f, "MIFARE Mini 0.3K", {1, -1} }, { 0x0004, 0xff0f, "MIFARE Classic 1K", {2, -1} }, { 0x0002, 0xff0f, "MIFARE Classic 4K", {3, -1} }, { 0x0004, 0xffff, "MIFARE Plus (4 Byte UID or 4 Byte RID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0002, 0xffff, "MIFARE Plus (4 Byte UID or 4 Byte RID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0044, 0xffff, "MIFARE Plus (7 Byte UID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0042, 0xffff, "MIFARE Plus (7 Byte UID)", {4, 5, 6, 7, 8, 9, -1} }, { 0x0344, 0xffff, "MIFARE DESFire", {10, 11, -1} }, { 0x0044, 0xffff, "P3SR008", { -1} }, // TODO we need SAK info { 0x0004, 0xf0ff, "SmartMX with MIFARE 1K emulation", {12, -1} }, { 0x0002, 0xf0ff, "SmartMX with MIFARE 4K emulation", {12, -1} }, { 0x0048, 0xf0ff, "SmartMX with 7 Byte UID", {12, -1} } }; struct card_sak const_cs[] = { {0x00, 0xff, "" }, // 00 MIFARE Ultralight / Ultralight C {0x09, 0xff, "" }, // 01 MIFARE Mini 0.3K {0x08, 0xff, "" }, // 02 MIFARE Classic 1K {0x18, 0xff, "" }, // 03 MIFARE Classik 4K {0x08, 0xff, " 2K, Security level 1" }, // 04 MIFARE Plus {0x18, 0xff, " 4K, Security level 1" }, // 05 MIFARE Plus {0x10, 0xff, " 2K, Security level 2" }, // 06 MIFARE Plus {0x11, 0xff, " 4K, Security level 2" }, // 07 MIFARE Plus {0x20, 0xff, " 2K, Security level 3" }, // 08 MIFARE Plus {0x20, 0xff, " 4K, Security level 3" }, // 09 MIFARE Plus {0x20, 0xff, " 4K" }, // 10 MIFARE DESFire {0x20, 0xff, " EV1 2K/4K/8K" }, // 11 MIFARE DESFire {0x00, 0x00, "" }, // 12 SmartMX }; int snprint_hex(char *dst, size_t size, const uint8_t *pbtData, const size_t szBytes) { size_t szPos; size_t res = 0; for (szPos = 0; szPos < szBytes; szPos++) { res += snprintf(dst + res, size - res, "%02x ", pbtData[szPos]); } res += snprintf(dst + res, size - res, "\n"); return res; } #define SAK_UID_NOT_COMPLETE 0x04 #define SAK_ISO14443_4_COMPLIANT 0x20 #define SAK_ISO18092_COMPLIANT 0x40 void snprint_nfc_iso14443a_info(char *dst, size_t size, const nfc_iso14443a_info *pnai, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " ATQA (SENS_RES): "); off += snprint_hex(dst + off, size - off, pnai->abtAtqa, 2); if (verbose) { off += snprintf(dst + off, size - off, "* UID size: "); switch ((pnai->abtAtqa[1] & 0xc0) >> 6) { case 0: off += snprintf(dst + off, size - off, "single\n"); break; case 1: off += snprintf(dst + off, size - off, "double\n"); break; case 2: off += snprintf(dst + off, size - off, "triple\n"); break; case 3: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, "* bit frame anticollision "); switch (pnai->abtAtqa[1] & 0x1f) { case 0x01: case 0x02: case 0x04: case 0x08: case 0x10: off += snprintf(dst + off, size - off, "supported\n"); break; default: off += snprintf(dst + off, size - off, "not supported\n"); break; } } off += snprintf(dst + off, size - off, " UID (NFCID%c): ", (pnai->abtUid[0] == 0x08 ? '3' : '1')); off += snprint_hex(dst + off, size - off, pnai->abtUid, pnai->szUidLen); if (verbose) { if (pnai->abtUid[0] == 0x08) { off += snprintf(dst + off, size - off, "* Random UID\n"); } } off += snprintf(dst + off, size - off, " SAK (SEL_RES): "); off += snprint_hex(dst + off, size - off, &pnai->btSak, 1); if (verbose) { if (pnai->btSak & SAK_UID_NOT_COMPLETE) { off += snprintf(dst + off, size - off, "* Warning! Cascade bit set: UID not complete\n"); } if (pnai->btSak & SAK_ISO14443_4_COMPLIANT) { off += snprintf(dst + off, size - off, "* Compliant with ISO/IEC 14443-4\n"); } else { off += snprintf(dst + off, size - off, "* Not compliant with ISO/IEC 14443-4\n"); } if (pnai->btSak & SAK_ISO18092_COMPLIANT) { off += snprintf(dst + off, size - off, "* Compliant with ISO/IEC 18092\n"); } else { off += snprintf(dst + off, size - off, "* Not compliant with ISO/IEC 18092\n"); } } if (pnai->szAtsLen) { off += snprintf(dst + off, size - off, " ATS: "); off += snprint_hex(dst + off, size - off, pnai->abtAts, pnai->szAtsLen); } if (pnai->szAtsLen && verbose) { // Decode ATS according to ISO/IEC 14443-4 (5.2 Answer to select) const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; off += snprintf(dst + off, size - off, "* Max Frame Size accepted by PICC: %d bytes\n", iMaxFrameSizes[pnai->abtAts[0] & 0x0F]); size_t offset = 1; if (pnai->abtAts[0] & 0x10) { // TA(1) present uint8_t TA = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, "* Bit Rate Capability:\n"); if (TA == 0) { off += snprintf(dst + off, size - off, " * PICC supports only 106 kbits/s in both directions\n"); } if (TA & 1 << 7) { off += snprintf(dst + off, size - off, " * Same bitrate in both directions mandatory\n"); } if (TA & 1 << 4) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=2, bitrate 212 kbits/s supported\n"); } if (TA & 1 << 5) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=4, bitrate 424 kbits/s supported\n"); } if (TA & 1 << 6) { off += snprintf(dst + off, size - off, " * PICC to PCD, DS=8, bitrate 847 kbits/s supported\n"); } if (TA & 1 << 0) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=2, bitrate 212 kbits/s supported\n"); } if (TA & 1 << 1) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=4, bitrate 424 kbits/s supported\n"); } if (TA & 1 << 2) { off += snprintf(dst + off, size - off, " * PCD to PICC, DR=8, bitrate 847 kbits/s supported\n"); } if (TA & 1 << 3) { off += snprintf(dst + off, size - off, " * ERROR unknown value\n"); } } if (pnai->abtAts[0] & 0x20) { // TB(1) present uint8_t TB = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, "* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((TB & 0xf0) >> 4)) / 13560.0); if ((TB & 0x0f) == 0) { off += snprintf(dst + off, size - off, "* No Start-up Frame Guard Time required\n"); } else { off += snprintf(dst + off, size - off, "* Start-up Frame Guard Time: %.4g ms\n", 256.0 * 16.0 * (1 << (TB & 0x0f)) / 13560.0); } } if (pnai->abtAts[0] & 0x40) { // TC(1) present uint8_t TC = pnai->abtAts[offset]; offset++; if (TC & 0x1) { off += snprintf(dst + off, size - off, "* Node Address supported\n"); } else { off += snprintf(dst + off, size - off, "* Node Address not supported\n"); } if (TC & 0x2) { off += snprintf(dst + off, size - off, "* Card IDentifier supported\n"); } else { off += snprintf(dst + off, size - off, "* Card IDentifier not supported\n"); } } if (pnai->szAtsLen > offset) { off += snprintf(dst + off, size - off, "* Historical bytes Tk: "); off += snprint_hex(dst + off, size - off, pnai->abtAts + offset, (pnai->szAtsLen - offset)); uint8_t CIB = pnai->abtAts[offset]; offset++; if (CIB != 0x00 && CIB != 0x10 && (CIB & 0xf0) != 0x80) { off += snprintf(dst + off, size - off, " * Proprietary format\n"); if (CIB == 0xc1) { off += snprintf(dst + off, size - off, " * Tag byte: Mifare or virtual cards of various types\n"); uint8_t L = pnai->abtAts[offset]; offset++; if (L != (pnai->szAtsLen - offset)) { off += snprintf(dst + off, size - off, " * Warning: Type Identification Coding length (%i)", L); off += snprintf(dst + off, size - off, " not matching Tk length (%" PRIdPTR ")\n", (pnai->szAtsLen - offset)); } if ((pnai->szAtsLen - offset - 2) > 0) { // Omit 2 CRC bytes uint8_t CTC = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Chip Type: "); switch (CTC & 0xf0) { case 0x00: off += snprintf(dst + off, size - off, "(Multiple) Virtual Cards\n"); break; case 0x10: off += snprintf(dst + off, size - off, "Mifare DESFire\n"); break; case 0x20: off += snprintf(dst + off, size - off, "Mifare Plus\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, " * Memory size: "); switch (CTC & 0x0f) { case 0x00: off += snprintf(dst + off, size - off, "<1 kbyte\n"); break; case 0x01: off += snprintf(dst + off, size - off, "1 kbyte\n"); break; case 0x02: off += snprintf(dst + off, size - off, "2 kbyte\n"); break; case 0x03: off += snprintf(dst + off, size - off, "4 kbyte\n"); break; case 0x04: off += snprintf(dst + off, size - off, "8 kbyte\n"); break; case 0x0f: off += snprintf(dst + off, size - off, "Unspecified\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } } if ((pnai->szAtsLen - offset) > 0) { // Omit 2 CRC bytes uint8_t CVC = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Chip Status: "); switch (CVC & 0xf0) { case 0x00: off += snprintf(dst + off, size - off, "Engineering sample\n"); break; case 0x20: off += snprintf(dst + off, size - off, "Released\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } off += snprintf(dst + off, size - off, " * Chip Generation: "); switch (CVC & 0x0f) { case 0x00: off += snprintf(dst + off, size - off, "Generation 1\n"); break; case 0x01: off += snprintf(dst + off, size - off, "Generation 2\n"); break; case 0x02: off += snprintf(dst + off, size - off, "Generation 3\n"); break; case 0x0f: off += snprintf(dst + off, size - off, "Unspecified\n"); break; default: off += snprintf(dst + off, size - off, "RFU\n"); break; } } if ((pnai->szAtsLen - offset) > 0) { // Omit 2 CRC bytes uint8_t VCS = pnai->abtAts[offset]; offset++; off += snprintf(dst + off, size - off, " * Specifics (Virtual Card Selection):\n"); if ((VCS & 0x09) == 0x00) { off += snprintf(dst + off, size - off, " * Only VCSL supported\n"); } else if ((VCS & 0x09) == 0x01) { off += snprintf(dst + off, size - off, " * VCS, VCSL and SVC supported\n"); } if ((VCS & 0x0e) == 0x00) { off += snprintf(dst + off, size - off, " * SL1, SL2(?), SL3 supported\n"); } else if ((VCS & 0x0e) == 0x02) { off += snprintf(dst + off, size - off, " * SL3 only card\n"); } else if ((VCS & 0x0f) == 0x0e) { off += snprintf(dst + off, size - off, " * No VCS command supported\n"); } else if ((VCS & 0x0f) == 0x0f) { off += snprintf(dst + off, size - off, " * Unspecified\n"); } else { off += snprintf(dst + off, size - off, " * RFU\n"); } } } } else { if (CIB == 0x00) { off += snprintf(dst + off, size - off, " * Tk after 0x00 consist of optional consecutive COMPACT-TLV data objects\n"); off += snprintf(dst + off, size - off, " followed by a mandatory status indicator (the last three bytes, not in TLV)\n"); off += snprintf(dst + off, size - off, " See ISO/IEC 7816-4 8.1.1.3 for more info\n"); } if (CIB == 0x10) { off += snprintf(dst + off, size - off, " * DIR data reference: %02x\n", pnai->abtAts[offset]); } if (CIB == 0x80) { if (pnai->szAtsLen == offset) { off += snprintf(dst + off, size - off, " * No COMPACT-TLV objects found, no status found\n"); } else { off += snprintf(dst + off, size - off, " * Tk after 0x80 consist of optional consecutive COMPACT-TLV data objects;\n"); off += snprintf(dst + off, size - off, " the last data object may carry a status indicator of one, two or three bytes.\n"); off += snprintf(dst + off, size - off, " See ISO/IEC 7816-4 8.1.1.3 for more info\n"); } } } } } if (verbose) { off += snprintf(dst + off, size - off, "\nFingerprinting based on MIFARE type Identification Procedure:\n"); // AN10833 uint16_t atqa = 0; uint8_t sak = 0; uint8_t i, j; bool found_possible_match = false; atqa = (((uint16_t)pnai->abtAtqa[0] & 0xff) << 8); atqa += (((uint16_t)pnai->abtAtqa[1] & 0xff)); sak = ((uint8_t)pnai->btSak & 0xff); for (i = 0; i < sizeof(const_ca) / sizeof(const_ca[0]); i++) { if ((atqa & const_ca[i].mask) == const_ca[i].atqa) { for (j = 0; (j < sizeof(const_ca[i].saklist)) && (const_ca[i].saklist[j] >= 0); j++) { int sakindex = const_ca[i].saklist[j]; if ((sak & const_cs[sakindex].mask) == const_cs[sakindex].sak) { off += snprintf(dst + off, size - off, "* %s%s\n", const_ca[i].type, const_cs[sakindex].type); found_possible_match = true; } } } } // Other matches not described in // AN10833 MIFARE Type Identification Procedure // but seen in the field: off += snprintf(dst + off, size - off, "Other possible matches based on ATQA & SAK values:\n"); uint32_t atqasak = 0; atqasak += (((uint32_t)pnai->abtAtqa[0] & 0xff) << 16); atqasak += (((uint32_t)pnai->abtAtqa[1] & 0xff) << 8); atqasak += ((uint32_t)pnai->btSak & 0xff); switch (atqasak) { case 0x000488: off += snprintf(dst + off, size - off, "* Mifare Classic 1K Infineon\n"); found_possible_match = true; break; case 0x000298: off += snprintf(dst + off, size - off, "* Gemplus MPCOS\n"); found_possible_match = true; break; case 0x030428: off += snprintf(dst + off, size - off, "* JCOP31\n"); found_possible_match = true; break; case 0x004820: off += snprintf(dst + off, size - off, "* JCOP31 v2.4.1\n"); off += snprintf(dst + off, size - off, "* JCOP31 v2.2\n"); found_possible_match = true; break; case 0x000428: off += snprintf(dst + off, size - off, "* JCOP31 v2.3.1\n"); found_possible_match = true; break; case 0x000453: off += snprintf(dst + off, size - off, "* Fudan FM1208SH01\n"); found_possible_match = true; break; case 0x000820: off += snprintf(dst + off, size - off, "* Fudan FM1208\n"); found_possible_match = true; break; case 0x000238: off += snprintf(dst + off, size - off, "* MFC 4K emulated by Nokia 6212 Classic\n"); found_possible_match = true; break; case 0x000838: off += snprintf(dst + off, size - off, "* MFC 4K emulated by Nokia 6131 NFC\n"); found_possible_match = true; break; } if (! found_possible_match) { snprintf(dst + off, size - off, "* Unknown card, sorry\n"); } } } void snprint_nfc_felica_info(char *dst, size_t size, const nfc_felica_info *pnfi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " ID (NFCID2): "); off += snprint_hex(dst + off, size - off, pnfi->abtId, 8); off += snprintf(dst + off, size - off, " Parameter (PAD): "); off += snprint_hex(dst + off, size - off, pnfi->abtPad, 8); off += snprintf(dst + off, size - off, " System Code (SC): "); snprint_hex(dst + off, size - off, pnfi->abtSysCode, 2); } void snprint_nfc_jewel_info(char *dst, size_t size, const nfc_jewel_info *pnji, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " ATQA (SENS_RES): "); off += snprint_hex(dst + off, size - off, pnji->btSensRes, 2); off += snprintf(dst + off, size - off, " 4-LSB JEWELID: "); snprint_hex(dst + off, size - off, pnji->btId, 4); } #define PI_ISO14443_4_SUPPORTED 0x01 #define PI_NAD_SUPPORTED 0x01 #define PI_CID_SUPPORTED 0x02 void snprint_nfc_iso14443b_info(char *dst, size_t size, const nfc_iso14443b_info *pnbi, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " PUPI: "); off += snprint_hex(dst + off, size - off, pnbi->abtPupi, 4); off += snprintf(dst + off, size - off, " Application Data: "); off += snprint_hex(dst + off, size - off, pnbi->abtApplicationData, 4); off += snprintf(dst + off, size - off, " Protocol Info: "); off += snprint_hex(dst + off, size - off, pnbi->abtProtocolInfo, 3); if (verbose) { off += snprintf(dst + off, size - off, "* Bit Rate Capability:\n"); if (pnbi->abtProtocolInfo[0] == 0) { off += snprintf(dst + off, size - off, " * PICC supports only 106 kbits/s in both directions\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 7) { off += snprintf(dst + off, size - off, " * Same bitrate in both directions mandatory\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 4) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=64/fc, bitrate 212 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 5) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=32/fc, bitrate 424 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 6) { off += snprintf(dst + off, size - off, " * PICC to PCD, 1etu=16/fc, bitrate 847 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 0) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=64/fc, bitrate 212 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 1) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=32/fc, bitrate 424 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 2) { off += snprintf(dst + off, size - off, " * PCD to PICC, 1etu=16/fc, bitrate 847 kbits/s supported\n"); } if (pnbi->abtProtocolInfo[0] & 1 << 3) { off += snprintf(dst + off, size - off, " * ERROR unknown value\n"); } if ((pnbi->abtProtocolInfo[1] & 0xf0) <= 0x80) { const int iMaxFrameSizes[] = { 16, 24, 32, 40, 48, 64, 96, 128, 256 }; off += snprintf(dst + off, size - off, "* Maximum frame sizes: %d bytes\n", iMaxFrameSizes[((pnbi->abtProtocolInfo[1] & 0xf0) >> 4)]); } if ((pnbi->abtProtocolInfo[1] & 0x0f) == PI_ISO14443_4_SUPPORTED) { off += snprintf(dst + off, size - off, "* Protocol types supported: ISO/IEC 14443-4\n"); } off += snprintf(dst + off, size - off, "* Frame Waiting Time: %.4g ms\n", 256.0 * 16.0 * (1 << ((pnbi->abtProtocolInfo[2] & 0xf0) >> 4)) / 13560.0); if ((pnbi->abtProtocolInfo[2] & (PI_NAD_SUPPORTED | PI_CID_SUPPORTED)) != 0) { off += snprintf(dst + off, size - off, "* Frame options supported: "); if ((pnbi->abtProtocolInfo[2] & PI_NAD_SUPPORTED) != 0) off += snprintf(dst + off, size - off, "NAD "); if ((pnbi->abtProtocolInfo[2] & PI_CID_SUPPORTED) != 0) off += snprintf(dst + off, size - off, "CID "); snprintf(dst + off, size - off, "\n"); } } } void snprint_nfc_iso14443bi_info(char *dst, size_t size, const nfc_iso14443bi_info *pnii, bool verbose) { int off = 0; off += snprintf(dst + off, size - off, " DIV: "); off += snprint_hex(dst + off, size - off, pnii->abtDIV, 4); if (verbose) { int version = (pnii->btVerLog & 0x1e) >> 1; off += snprintf(dst + off, size - off, " Software Version: "); if (version == 15) { off += snprintf(dst + off, size - off, "Undefined\n"); } else { off += snprintf(dst + off, size - off, "%i\n", version); } if ((pnii->btVerLog & 0x80) && (pnii->btConfig & 0x80)) { off += snprintf(dst + off, size - off, " Wait Enable: yes"); } } if ((pnii->btVerLog & 0x80) && (pnii->btConfig & 0x40)) { off += snprintf(dst + off, size - off, " ATS: "); snprint_hex(dst + off, size - off, pnii->abtAtr, pnii->szAtrLen); } } void snprint_nfc_iso14443b2sr_info(char *dst, size_t size, const nfc_iso14443b2sr_info *pnsi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " UID: "); snprint_hex(dst + off, size - off, pnsi->abtUID, 8); } void snprint_nfc_iso14443b2ct_info(char *dst, size_t size, const nfc_iso14443b2ct_info *pnci, bool verbose) { (void) verbose; int off = 0; uint32_t uid; uid = (pnci->abtUID[3] << 24) + (pnci->abtUID[2] << 16) + (pnci->abtUID[1] << 8) + pnci->abtUID[0]; off += snprintf(dst + off, size - off, " UID: "); off += snprint_hex(dst + off, size - off, pnci->abtUID, sizeof(pnci->abtUID)); off += snprintf(dst + off, size - off, " UID (decimal): %010u\n", uid); off += snprintf(dst + off, size - off, " Product Code: %02X\n", pnci->btProdCode); snprintf(dst + off, size - off, " Fab Code: %02X\n", pnci->btFabCode); } void snprint_nfc_dep_info(char *dst, size_t size, const nfc_dep_info *pndi, bool verbose) { (void) verbose; int off = 0; off += snprintf(dst + off, size - off, " NFCID3: "); off += snprint_hex(dst + off, size - off, pndi->abtNFCID3, 10); off += snprintf(dst + off, size - off, " BS: %02x\n", pndi->btBS); off += snprintf(dst + off, size - off, " BR: %02x\n", pndi->btBR); off += snprintf(dst + off, size - off, " TO: %02x\n", pndi->btTO); off += snprintf(dst + off, size - off, " PP: %02x\n", pndi->btPP); if (pndi->szGB) { off += snprintf(dst + off, size - off, "General Bytes: "); snprint_hex(dst + off, size - off, pndi->abtGB, pndi->szGB); } } void snprint_nfc_target(char *dst, size_t size, const nfc_target *pnt, bool verbose) { if (NULL != pnt) { int off = 0; off += snprintf(dst + off, size - off, "%s (%s%s) target:\n", str_nfc_modulation_type(pnt->nm.nmt), str_nfc_baud_rate(pnt->nm.nbr), (pnt->nm.nmt != NMT_DEP) ? "" : (pnt->nti.ndi.ndm == NDM_ACTIVE) ? "active mode" : "passive mode"); switch (pnt->nm.nmt) { case NMT_ISO14443A: snprint_nfc_iso14443a_info(dst + off, size - off, &pnt->nti.nai, verbose); break; case NMT_JEWEL: snprint_nfc_jewel_info(dst + off, size - off, &pnt->nti.nji, verbose); break; case NMT_FELICA: snprint_nfc_felica_info(dst + off, size - off, &pnt->nti.nfi, verbose); break; case NMT_ISO14443B: snprint_nfc_iso14443b_info(dst + off, size - off, &pnt->nti.nbi, verbose); break; case NMT_ISO14443BI: snprint_nfc_iso14443bi_info(dst + off, size - off, &pnt->nti.nii, verbose); break; case NMT_ISO14443B2SR: snprint_nfc_iso14443b2sr_info(dst + off, size - off, &pnt->nti.nsi, verbose); break; case NMT_ISO14443B2CT: snprint_nfc_iso14443b2ct_info(dst + off, size - off, &pnt->nti.nci, verbose); break; case NMT_DEP: snprint_nfc_dep_info(dst + off, size - off, &pnt->nti.ndi, verbose); break; } } }
zzyjames55-nfc0805
libnfc/target-subr.c
C
lgpl
26,179
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file mirror-subr.c * @brief Mirror bytes */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include "mirror-subr.h" static const uint8_t ByteMirror[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; uint8_t mirror(uint8_t bt) { return ByteMirror[bt]; } static void mirror_bytes(uint8_t *pbts, size_t szLen) { size_t szByteNr; for (szByteNr = 0; szByteNr < szLen; szByteNr++) { *pbts = ByteMirror[*pbts]; pbts++; } } uint32_t mirror32(uint32_t ui32Bits) { mirror_bytes((uint8_t *) & ui32Bits, 4); return ui32Bits; } uint64_t mirror64(uint64_t ui64Bits) { mirror_bytes((uint8_t *) & ui64Bits, 8); return ui64Bits; }
zzyjames55-nfc0805
libnfc/mirror-subr.c
C
lgpl
3,312
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "conf.h" #ifdef CONFFILES #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <string.h> #include <regex.h> #include <sys/stat.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "log.h" #define LOG_CATEGORY "libnfc.config" #define LOG_GROUP NFC_LOG_GROUP_CONFIG #ifndef LIBNFC_SYSCONFDIR // If this define does not already exists, we build it using SYSCONFDIR #ifndef SYSCONFDIR #error "SYSCONFDIR is not defined but required." #endif // SYSCONFDIR #define LIBNFC_SYSCONFDIR SYSCONFDIR"/nfc" #endif // LIBNFC_SYSCONFDIR #define LIBNFC_CONFFILE LIBNFC_SYSCONFDIR"/libnfc.conf" #define LIBNFC_DEVICECONFDIR LIBNFC_SYSCONFDIR"/devices.d" static bool conf_parse_file(const char *filename, void (*conf_keyvalue)(void *data, const char *key, const char *value), void *data) { FILE *f = fopen(filename, "r"); if (!f) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Unable to open file: %s", filename); return false; } char line[BUFSIZ]; const char *str_regex = "^[[:space:]]*([[:alnum:]_.]+)[[:space:]]*=[[:space:]]*(\"(.+)\"|([^[:space:]]+))[[:space:]]*$"; regex_t preg; if (regcomp(&preg, str_regex, REG_EXTENDED | REG_NOTEOL) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Regular expression used for configuration file parsing is not valid."); fclose(f); return false; } size_t nmatch = preg.re_nsub + 1; regmatch_t *pmatch = malloc(sizeof(*pmatch) * nmatch); if (!pmatch) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Not enough memory: malloc failed."); regfree(&preg); fclose(f); return false; } int lineno = 0; while (fgets(line, BUFSIZ, f) != NULL) { lineno++; switch (line[0]) { case '#': case '\n': break; default: { int match; if ((match = regexec(&preg, line, nmatch, pmatch, 0)) == 0) { const size_t key_size = pmatch[1].rm_eo - pmatch[1].rm_so; const off_t value_pmatch = pmatch[3].rm_eo != -1 ? 3 : 4; const size_t value_size = pmatch[value_pmatch].rm_eo - pmatch[value_pmatch].rm_so; char key[key_size + 1]; char value[value_size + 1]; strncpy(key, line + (pmatch[1].rm_so), key_size); key[key_size] = '\0'; strncpy(value, line + (pmatch[value_pmatch].rm_so), value_size); value[value_size] = '\0'; conf_keyvalue(data, key, value); } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Parse error on line #%d: %s", lineno, line); } } break; } } free(pmatch); regfree(&preg); fclose(f); return false; } static void conf_keyvalue_context(void *data, const char *key, const char *value) { nfc_context *context = (nfc_context *)data; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "key: [%s], value: [%s]", key, value); if (strcmp(key, "allow_autoscan") == 0) { string_as_boolean(value, &(context->allow_autoscan)); } else if (strcmp(key, "allow_intrusive_scan") == 0) { string_as_boolean(value, &(context->allow_intrusive_scan)); } else if (strcmp(key, "log_level") == 0) { context->log_level = atoi(value); } else if (strcmp(key, "device.name") == 0) { if ((context->user_defined_device_count == 0) || strcmp(context->user_defined_devices[context->user_defined_device_count - 1].name, "") != 0) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } strcpy(context->user_defined_devices[context->user_defined_device_count - 1].name, value); } else if (strcmp(key, "device.connstring") == 0) { if ((context->user_defined_device_count == 0) || strcmp(context->user_defined_devices[context->user_defined_device_count - 1].connstring, "") != 0) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } strcpy(context->user_defined_devices[context->user_defined_device_count - 1].connstring, value); } else if (strcmp(key, "device.optional") == 0) { if ((context->user_defined_device_count == 0) || context->user_defined_devices[context->user_defined_device_count - 1].optional) { if (context->user_defined_device_count >= MAX_USER_DEFINED_DEVICES) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Configuration exceeded maximum user-defined devices."); return; } context->user_defined_device_count++; } if ((strcmp(value, "true") == 0) || (strcmp(value, "True") == 0) || (strcmp(value, "1") == 0)) //optional context->user_defined_devices[context->user_defined_device_count - 1].optional = true; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Unknown key in config line: %s = %s", key, value); } } static void conf_keyvalue_device(void *data, const char *key, const char *value) { char newkey[BUFSIZ]; sprintf(newkey, "device.%s", key); conf_keyvalue_context(data, newkey, value); } static void conf_devices_load(const char *dirname, nfc_context *context) { DIR *d = opendir(dirname); if (!d) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Unable to open directory: %s", dirname); } else { struct dirent *de; struct dirent entry; struct dirent *result; while ((readdir_r(d, &entry, &result) == 0) && (result != NULL)) { de = &entry; if (de->d_name[0] != '.') { const size_t filename_len = strlen(de->d_name); const size_t extension_len = strlen(".conf"); if ((filename_len > extension_len) && (strncmp(".conf", de->d_name + (filename_len - extension_len), extension_len) == 0)) { char filename[BUFSIZ] = LIBNFC_DEVICECONFDIR"/"; strcat(filename, de->d_name); struct stat s; if (stat(filename, &s) == -1) { perror("stat"); continue; } if (S_ISREG(s.st_mode)) { conf_parse_file(filename, conf_keyvalue_device, context); } } } } closedir(d); } } void conf_load(nfc_context *context) { conf_parse_file(LIBNFC_CONFFILE, conf_keyvalue_context, context); conf_devices_load(LIBNFC_DEVICECONFDIR, context); } #endif // CONFFILES
zzyjames55-nfc0805
libnfc/conf.c
C
lgpl
7,800
# Windows MinGW workarounds IF(WIN32) SET(WINDOWS_SOURCES ../contrib/win32/stdlib) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32) # Add in the rc for version information in the dll LIST(APPEND WINDOWS_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/../windows/libnfc.rc) ENDIF(WIN32) # Library's chips SET(CHIPS_SOURCES chips/pn53x) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/chips) # Library's buses IF(USB_REQUIRED) LIST(APPEND BUSES_SOURCES buses/usbbus) ENDIF(USB_REQUIRED) IF(UART_REQUIRED) IF(WIN32) # Windows have a special implementation for UART LIST(APPEND BUSES_SOURCES ../contrib/win32/libnfc/buses/uart) ELSE(WIN32) LIST(APPEND BUSES_SOURCES buses/uart) ENDIF(WIN32) ENDIF(UART_REQUIRED) IF(I2C_REQUIRED) IF(WIN32) # Windows is not supported at the moment #LIST(APPEND BUSES_SOURCES ../contrib/win32/libnfc/buses/i2c) MESSAGE( FATAL_ERROR "I2C not (yet) supported under Windows!" ) ELSE(WIN32) LIST(APPEND BUSES_SOURCES buses/i2c) ENDIF(WIN32) ENDIF(I2C_REQUIRED) IF(SPI_REQUIRED) IF(WIN32) # Windows is not supported at the moment #LIST(APPEND BUSES_SOURCES ../contrib/win32/libnfc/buses/spi) MESSAGE( FATAL_ERROR "SPI not (yet) supported under Windows!" ) ELSE(WIN32) LIST(APPEND BUSES_SOURCES buses/spi) ENDIF(WIN32) ENDIF(SPI_REQUIRED) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/buses) IF(WIN32) # Windows now requires regex, so we utilize PCRE # since Windows doesn't get the benefit of finding in CMake # it has to be added manually IF(PCRE_FOUND) INCLUDE_DIRECTORIES(${PCRE_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCRE_LIBRARY_DIRS}) ENDIF(PCRE_FOUND) ENDIF(WIN32) IF(PCSC_FOUND) INCLUDE_DIRECTORIES(${PCSC_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCSC_LIBRARY_DIRS}) ENDIF(PCSC_FOUND) IF(LIBUSB_FOUND) INCLUDE_DIRECTORIES(${LIBUSB_INCLUDE_DIRS}) LINK_DIRECTORIES(${LIBUSB_LIBRARY_DIRS}) ENDIF(LIBUSB_FOUND) # Library SET(LIBRARY_SOURCES nfc nfc-device nfc-emulation nfc-internal conf iso14443-subr mirror-subr target-subr ${DRIVERS_SOURCES} ${BUSES_SOURCES} ${CHIPS_SOURCES} ${WINDOWS_SOURCES}) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) IF(LIBNFC_LOG) IF(WIN32) SET(CMAKE_C_FLAGS "-fgnu89-inline ${CMAKE_C_FLAGS}") LIST(APPEND LIBRARY_SOURCES log ../contrib/win32/libnfc/log-internal) ELSE(WIN32) LIST(APPEND LIBRARY_SOURCES log log-internal) ENDIF(WIN32) ENDIF(LIBNFC_LOG) ADD_LIBRARY(nfc SHARED ${LIBRARY_SOURCES}) IF(PCSC_FOUND) TARGET_LINK_LIBRARIES(nfc ${PCSC_LIBRARIES}) ENDIF(PCSC_FOUND) IF(LIBUSB_FOUND) TARGET_LINK_LIBRARIES(nfc ${LIBUSB_LIBRARIES}) ENDIF(LIBUSB_FOUND) SET_TARGET_PROPERTIES(nfc PROPERTIES SOVERSION 0) IF(WIN32) # Libraries that are windows specific TARGET_LINK_LIBRARIES(nfc wsock32) IF(PCRE_FOUND) TARGET_LINK_LIBRARIES(nfc ${PCRE_LIBRARIES}) ENDIF(PCRE_FOUND) ADD_CUSTOM_COMMAND( OUTPUT libnfc.lib COMMAND dlltool -d ${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32/nfc.def -l ${CMAKE_CURRENT_BINARY_DIR}/libnfc.lib ${CMAKE_CURRENT_BINARY_DIR}/libnfc.dll DEPENDS nfc ${CMAKE_CURRENT_SOURCE_DIR}/../contrib/win32/nfc.def ) ADD_CUSTOM_TARGET(win32lib ALL DEPENDS libnfc.lib) # On Windows the shared (runtime) library should be either in the same # directory as the excutables or in the path, we add it to same directory INSTALL(TARGETS nfc RUNTIME DESTINATION bin COMPONENT libraries) # At compile time we need the .LIB file, we place it in the lib directory INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/libnfc.lib DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) ELSE(WIN32) INSTALL(TARGETS nfc LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT libraries) ENDIF(WIN32)
zzyjames55-nfc0805
libnfc/CMakeLists.txt
CMake
lgpl
3,718
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-internal.c * @brief Provide some useful internal functions */ #include <nfc/nfc.h> #include "nfc-internal.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef CONFFILES #include "conf.h" #endif #include <stdlib.h> #include <string.h> #include <inttypes.h> #define LOG_GROUP NFC_LOG_GROUP_GENERAL #define LOG_CATEGORY "libnfc.general" void string_as_boolean(const char *s, bool *value) { if (s) { if (!(*value)) { if ((strcmp(s, "yes") == 0) || (strcmp(s, "true") == 0) || (strcmp(s, "1") == 0)) { *value = true; return; } } else { if ((strcmp(s, "no") == 0) || (strcmp(s, "false") == 0) || (strcmp(s, "0") == 0)) { *value = false; return; } } } } nfc_context * nfc_context_new(void) { nfc_context *res = malloc(sizeof(*res)); if (!res) { return NULL; } // Set default context values res->allow_autoscan = true; res->allow_intrusive_scan = false; #ifdef DEBUG res->log_level = 3; #else res->log_level = 1; #endif // Clear user defined devices array for (int i = 0; i < MAX_USER_DEFINED_DEVICES; i++) { strcpy(res->user_defined_devices[i].name, ""); strcpy(res->user_defined_devices[i].connstring, ""); res->user_defined_devices[i].optional = false; } res->user_defined_device_count = 0; #ifdef ENVVARS // Load user defined device from environment variable at first char *envvar = getenv("LIBNFC_DEFAULT_DEVICE"); if (envvar) { strcpy(res->user_defined_devices[0].name, "user defined default device"); strcpy(res->user_defined_devices[0].connstring, envvar); res->user_defined_device_count++; } #endif // ENVVARS #ifdef CONFFILES // Load options from configuration file (ie. /etc/nfc/libnfc.conf) conf_load(res); #endif // CONFFILES #ifdef ENVVARS // Environment variables // Load "intrusive scan" option envvar = getenv("LIBNFC_INTRUSIVE_SCAN"); string_as_boolean(envvar, &(res->allow_intrusive_scan)); // log level envvar = getenv("LIBNFC_LOG_LEVEL"); if (envvar) { res->log_level = atoi(envvar); } #endif // ENVVARS // Initialize log before use it... log_init(res); // Debug context state #if defined DEBUG log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_NONE, "log_level is set to %"PRIu32, res->log_level); #else log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "log_level is set to %"PRIu32, res->log_level); #endif log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "allow_autoscan is set to %s", (res->allow_autoscan) ? "true" : "false"); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "allow_intrusive_scan is set to %s", (res->allow_intrusive_scan) ? "true" : "false"); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d device(s) defined by user", res->user_defined_device_count); for (uint32_t i = 0; i < res->user_defined_device_count; i++) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, " #%d name: \"%s\", connstring: \"%s\"", i, res->user_defined_devices[i].name, res->user_defined_devices[i].connstring); } return res; } void nfc_context_free(nfc_context *context) { log_exit(); free(context); } void prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t *pszInitiatorData) { switch (nm.nmt) { case NMT_ISO14443B: { // Application Family Identifier (AFI) must equals 0x00 in order to wakeup all ISO14443-B PICCs (see ISO/IEC 14443-3) *ppbtInitiatorData = (uint8_t *) "\x00"; *pszInitiatorData = 1; } break; case NMT_ISO14443BI: { // APGEN *ppbtInitiatorData = (uint8_t *) "\x01\x0b\x3f\x80"; *pszInitiatorData = 4; } break; case NMT_ISO14443B2SR: { // Get_UID *ppbtInitiatorData = (uint8_t *) "\x0b"; *pszInitiatorData = 1; } break; case NMT_ISO14443B2CT: { // SELECT-ALL *ppbtInitiatorData = (uint8_t *) "\x9F\xFF\xFF"; *pszInitiatorData = 3; } break; case NMT_FELICA: { // polling payload must be present (see ISO/IEC 18092 11.2.2.5) *ppbtInitiatorData = (uint8_t *) "\x00\xff\xff\x01\x00"; *pszInitiatorData = 5; } break; case NMT_ISO14443A: case NMT_JEWEL: case NMT_DEP: *ppbtInitiatorData = NULL; *pszInitiatorData = 0; break; } } int connstring_decode(const nfc_connstring connstring, const char *driver_name, const char *bus_name, char **pparam1, char **pparam2) { if (driver_name == NULL) { driver_name = ""; } if (bus_name == NULL) { bus_name = ""; } int n = strlen(connstring) + 1; char *param0 = malloc(n); if (param0 == NULL) { perror("malloc"); return 0; } char *param1 = malloc(n); if (param1 == NULL) { perror("malloc"); free(param0); return 0; } char *param2 = malloc(n); if (param2 == NULL) { perror("malloc"); free(param0); free(param1); return 0; } char format[32]; snprintf(format, sizeof(format), "%%%i[^:]:%%%i[^:]:%%%i[^:]", n - 1, n - 1, n - 1); int res = sscanf(connstring, format, param0, param1, param2); if (res < 1 || ((0 != strcmp(param0, driver_name)) && (bus_name != NULL) && (0 != strcmp(param0, bus_name)))) { // Driver name does not match. res = 0; } if (pparam1 != NULL) { if (res < 2) { free(param1); *pparam1 = NULL; } else { *pparam1 = param1; } } else { free(param1); } if (pparam2 != NULL) { if (res < 3) { free(param2); *pparam2 = NULL; } else { *pparam2 = param2; } } else { free(param2); } free(param0); return res; }
zzyjames55-nfc0805
libnfc/nfc-internal.c
C
lgpl
6,811
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef __NFC_CONF_H__ #define __NFC_CONF_H__ #include <nfc/nfc-types.h> void conf_load(nfc_context *context); #endif // __NFC_CONF_H__
zzyjames55-nfc0805
libnfc/conf.h
C
lgpl
1,221
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file target-subr.c * @brief Target-related subroutines. (ie. determine target type, print target, etc.) */ #ifndef _TARGET_SUBR_H_ #define _TARGET_SUBR_H_ int snprint_hex(char *dst, size_t size, const uint8_t *pbtData, const size_t szLen); void snprint_nfc_iso14443a_info(char *dst, size_t size, const nfc_iso14443a_info *pnai, bool verbose); void snprint_nfc_iso14443b_info(char *dst, size_t size, const nfc_iso14443b_info *pnbi, bool verbose); void snprint_nfc_iso14443bi_info(char *dst, size_t size, const nfc_iso14443bi_info *pnii, bool verbose); void snprint_nfc_iso14443b2sr_info(char *dst, size_t size, const nfc_iso14443b2sr_info *pnsi, bool verbose); void snprint_nfc_iso14443b2ct_info(char *dst, size_t size, const nfc_iso14443b2ct_info *pnci, bool verbose); void snprint_nfc_felica_info(char *dst, size_t size, const nfc_felica_info *pnfi, bool verbose); void snprint_nfc_jewel_info(char *dst, size_t size, const nfc_jewel_info *pnji, bool verbose); void snprint_nfc_dep_info(char *dst, size_t size, const nfc_dep_info *pndi, bool verbose); void snprint_nfc_target(char *dst, size_t size, const nfc_target *pnt, bool verbose); #endif
zzyjames55-nfc0805
libnfc/target-subr.h
C
lgpl
2,271
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "log.h" #include <string.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <stdio.h> #include <stdarg.h> #include <fcntl.h> const char * log_priority_to_str(const int priority) { switch (priority) { case NFC_LOG_PRIORITY_ERROR: return "error"; case NFC_LOG_PRIORITY_INFO: return "info"; case NFC_LOG_PRIORITY_DEBUG: return "debug"; default: break; } return "unknown"; } #ifdef LOG #include "log-internal.h" void log_init(const nfc_context *context) { #ifdef ENVVARS char str[32]; sprintf(str, "%"PRIu32, context->log_level); setenv("LIBNFC_LOG_LEVEL", str, 1); #else (void)context; #endif } void log_exit(void) { } void log_put(const uint8_t group, const char *category, const uint8_t priority, const char *format, ...) { char *env_log_level = NULL; #ifdef ENVVARS env_log_level = getenv("LIBNFC_LOG_LEVEL"); #endif uint32_t log_level; if (NULL == env_log_level) { // LIBNFC_LOG_LEVEL is not set #ifdef DEBUG log_level = 3; #else log_level = 1; #endif } else { log_level = atoi(env_log_level); } // printf("log_level = %"PRIu32" group = %"PRIu8" priority = %"PRIu8"\n", log_level, group, priority); if (log_level) { // If log is not disabled by log_level=none if (((log_level & 0x00000003) >= priority) || // Global log level (((log_level >> (group * 2)) & 0x00000003) >= priority)) { // Group log level va_list va; va_start(va, format); log_put_internal("%s\t%s\t", log_priority_to_str(priority), category); log_vput_internal(format, va); log_put_internal("\n"); va_end(va); } } } #endif // LOG
zzyjames55-nfc0805
libnfc/log.c
C
lgpl
2,767
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-device.c * @brief Provide internal function to manipulate nfc_device type */ #include <stdlib.h> #include <string.h> #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "nfc-internal.h" nfc_device * nfc_device_new(const nfc_context *context, const nfc_connstring connstring) { nfc_device *res = malloc(sizeof(*res)); if (!res) { return NULL; } // Store associated context res->context = context; // Variables initiatialization // Note: Actually, these initialization will be overwritten while the device // will be setup. Putting them to _false_ while the default is _true_ ensure we // send the command to the chip res->bCrc = false; res->bPar = false; res->bEasyFraming = false; res->bAutoIso14443_4 = false; res->last_error = 0; memcpy(res->connstring, connstring, sizeof(res->connstring)); res->driver_data = NULL; res->chip_data = NULL; return res; } void nfc_device_free(nfc_device *dev) { if (dev) { free(dev->driver_data); free(dev); } }
zzyjames55-nfc0805
libnfc/nfc-device.c
C
lgpl
2,138
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file iso14443-subr.c * @brief Defines some function extracted for ISO/IEC 14443 */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdio.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" /** * @brief CRC * */ void iso14443a_crc(uint8_t *pbtData, size_t szLen, uint8_t *pbtCrc) { uint8_t bt; uint32_t wCrc = 0x6363; do { bt = *pbtData++; bt = (bt ^ (uint8_t)(wCrc & 0x00FF)); bt = (bt ^ (bt << 4)); wCrc = (wCrc >> 8) ^ ((uint32_t) bt << 8) ^ ((uint32_t) bt << 3) ^ ((uint32_t) bt >> 4); } while (--szLen); *pbtCrc++ = (uint8_t)(wCrc & 0xFF); *pbtCrc = (uint8_t)((wCrc >> 8) & 0xFF); } /** * @brief Append CRC * */ void iso14443a_crc_append(uint8_t *pbtData, size_t szLen) { iso14443a_crc(pbtData, szLen, pbtData + szLen); } /** * @brief Locate historical bytes * @see ISO/IEC 14443-4 (5.2.7 Historical bytes) */ uint8_t * iso14443a_locate_historical_bytes(uint8_t *pbtAts, size_t szAts, size_t *pszTk) { if (szAts) { size_t offset = 1; if (pbtAts[0] & 0x10) { // TA offset++; } if (pbtAts[0] & 0x20) { // TB offset++; } if (pbtAts[0] & 0x40) { // TC offset++; } if (szAts > offset) { *pszTk = (szAts - offset); return (pbtAts + offset); } } *pszTk = 0; return NULL; } /** * @brief Add cascade tags (0x88) in UID * @see ISO/IEC 14443-3 (6.4.4 UID contents and cascade levels) */ void iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID) { switch (szUID) { case 7: pbtCascadedUID[0] = 0x88; memcpy(pbtCascadedUID + 1, abtUID, 7); *pszCascadedUID = 8; break; case 10: pbtCascadedUID[0] = 0x88; memcpy(pbtCascadedUID + 1, abtUID, 3); pbtCascadedUID[4] = 0x88; memcpy(pbtCascadedUID + 5, abtUID + 3, 7); *pszCascadedUID = 12; break; case 4: default: memcpy(pbtCascadedUID, abtUID, szUID); *pszCascadedUID = szUID; break; } }
zzyjames55-nfc0805
libnfc/iso14443-subr.c
C
lgpl
3,146
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122s.h * @brief Driver for ACS ACR122S devices */ #ifndef __NFC_DRIVER_ACR122S_H__ #define __NFC_DRIVER_ACR122S_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122s_driver; #endif
zzyjames55-nfc0805
libnfc/drivers/acr122s.h
C
lgpl
1,301
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tarti?re * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Laurent Latil * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_i2c.c * @brief PN532 driver using I2C bus. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_i2c.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "buses/i2c.h" #define PN532_I2C_DRIVER_NAME "pn532_i2c" #define LOG_CATEGORY "libnfc.driver.pn532_i2c" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // I2C address of the PN532 chip. #define PN532_I2C_ADDR 0x24 // Internal data structs const struct pn53x_io pn532_i2c_io; struct pn532_i2c_data { i2c_device dev; volatile bool abort_flag; }; /* Delay for the loop waiting for READY frame (in ms) */ #define PN532_RDY_LOOP_DELAY 90 const struct timespec rdyDelay = { .tv_sec = 0, .tv_nsec = PN532_RDY_LOOP_DELAY * 1000 * 1000 }; /* Private Functions Prototypes */ static nfc_device *pn532_i2c_open(const nfc_context *context, const nfc_connstring connstring); static void pn532_i2c_close(nfc_device *pnd); static int pn532_i2c_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); static int pn532_i2c_ack(nfc_device *pnd); static int pn532_i2c_abort_command(nfc_device *pnd); static int pn532_i2c_wakeup(nfc_device *pnd); static int pn532_i2c_wait_rdyframe(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout); static size_t pn532_i2c_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len); #define DRIVER_DATA(pnd) ((struct pn532_i2c_data*)(pnd->driver_data)) /** * @brief Scan all available I2C buses to find PN532 devices. * * @param context NFC context. * @param connstrings array of 'nfc_connstring' buffer (allocated by caller). It is used to store the * connection info strings of all I2C PN532 devices found. * @param connstrings_len length of the connstrings array. * @return number of PN532 devices found on all I2C buses. */ static size_t pn532_i2c_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; i2c_device id; char **i2cPorts = i2c_list_ports(); const char *i2cPort; int iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { id = i2c_open(i2cPort, PN532_I2C_ADDR); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on I2C bus %s.", i2cPort); if ((id != INVALID_I2C_ADDRESS) && (id != INVALID_I2C_BUS)) { nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s", PN532_I2C_DRIVER_NAME, i2cPort); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); i2c_close(id); return 0; } pnd->driver = &pn532_i2c_driver; pnd->driver_data = malloc(sizeof(struct pn532_i2c_data)); if (!pnd->driver_data) { perror("malloc"); i2c_close(id); nfc_device_free(pnd); return 0; } DRIVER_DATA(pnd)->dev = id; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_i2c_io) == NULL) { perror("malloc"); i2c_close(DRIVER_DATA(pnd)->dev); nfc_device_free(pnd); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); i2c_close(DRIVER_DATA(pnd)->dev); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((i2cPort = i2cPorts[iDevice++])) { free((void *)i2cPort); } free(i2cPorts); return device_found; } /** * @brief Close I2C connection to the PN532 device. * * @param pnd pointer on the device to close. */ static void pn532_i2c_close(nfc_device *pnd) { pn53x_idle(pnd); i2c_close(DRIVER_DATA(pnd)->dev); pn53x_data_free(pnd); nfc_device_free(pnd); } /** * @brief Open an I2C connection to the PN532 device. * * @param context NFC context. * @param connstring connection info to the device ( pn532_i2c:<i2c_devname> ). * @return pointer to the device, or NULL in case of error. */ static nfc_device * pn532_i2c_open(const nfc_context *context, const nfc_connstring connstring) { char *i2c_devname; i2c_device i2c_dev; nfc_device *pnd; int connstring_decode_level = connstring_decode(connstring, PN532_I2C_DRIVER_NAME, NULL, &i2c_devname, NULL); switch (connstring_decode_level) { case 2: break; case 1: break; case 0: return NULL; } i2c_dev = i2c_open(i2c_devname, PN532_I2C_ADDR); if (i2c_dev == INVALID_I2C_BUS || i2c_dev == INVALID_I2C_ADDRESS) { return NULL; } pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); i2c_close(i2c_dev); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_I2C_DRIVER_NAME, i2c_devname); pnd->driver_data = malloc(sizeof(struct pn532_i2c_data)); if (!pnd->driver_data) { perror("malloc"); i2c_close(i2c_dev); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->dev = i2c_dev; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_i2c_io) == NULL) { perror("malloc"); i2c_close(i2c_dev); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_i2c_driver; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { nfc_perror(pnd, "pn53x_check_communication"); pn532_i2c_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } static int pn532_i2c_wakeup(nfc_device *pnd) { /* No specific. PN532 holds SCL during wakeup time */ CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake return NFC_SUCCESS; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) /** * @brief Send data to the PN532 device. * * @param pnd pointer on the NFC device. * @param pbtData buffer containing frame data. * @param szData size of the buffer. * @param timeout timeout before aborting the operation (in ms). * @return NFC_SUCCESS if operation is successful, or error code. */ static int pn532_i2c_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Discard any existing data ? switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_i2c_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_i2c_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = i2c_write(DRIVER_DATA(pnd)->dev, abtFrame, szFrame); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; // Wait for the ACK frame res = pn532_i2c_wait_rdyframe(pnd, abtRxBuf, sizeof(abtRxBuf), timeout); if (res < 0) { if (res == NFC_EOPABORTED) { // Send an ACK frame from host to abort the command. pn532_i2c_ack(pnd); } pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } /** * @brief Read data from the PN532 device until getting a frame with RDY bit set * * @param pnd pointer on the NFC device. * @param pbtData buffer used to store the received frame data. * @param szDataLen allocated size of buffer. * @param timeout timeout delay before aborting the operation (in ms). Use 0 for no timeout. * @return length (in bytes) of the received frame, or NFC_ETIMEOUT if timeout delay has expired, * NFC_EOPABORTED if operation has been aborted, NFC_EIO in case of IO failure */ static int pn532_i2c_wait_rdyframe(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { bool done = false; int res; struct timeval start_tv, cur_tv; long long duration; // Actual I2C response frame includes an additional status byte, // so we use a temporary buffer to read the I2C frame uint8_t i2cRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN + 1]; if (timeout > 0) { // If a timeout is specified, get current timestamp gettimeofday(&start_tv, NULL); } do { // Wait a little bit before reading nanosleep(&rdyDelay, (struct timespec *) NULL); int recCount = i2c_read(DRIVER_DATA(pnd)->dev, i2cRx, szDataLen + 1); if (DRIVER_DATA(pnd)->abort_flag) { // Reset abort flag DRIVER_DATA(pnd)->abort_flag = false; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Wait for a READY frame has been aborted."); return NFC_EOPABORTED; } if (recCount <= 0) { done = true; res = NFC_EIO; } else { const uint8_t rdy = i2cRx[0]; if (rdy & 1) { int copyLength; done = true; res = recCount - 1; copyLength = MIN(res, (int)szDataLen); memcpy(pbtData, &(i2cRx[1]), copyLength); } else { /* Not ready yet. Check for elapsed timeout. */ if (timeout > 0) { gettimeofday(&cur_tv, NULL); duration = (cur_tv.tv_sec - start_tv.tv_sec) * 1000000L + (cur_tv.tv_usec - start_tv.tv_usec); if (duration / 1000 > timeout) { res = NFC_ETIMEOUT; done = true; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "timeout reached with no READY frame."); } } } } } while (!done); return res; } /** * @brief Read a response frame from the PN532 device. * * @param pnd pointer on the NFC device. * @param pbtData buffer used to store the response frame data. * @param szDataLen allocated size of buffer. * @param timeout timeout delay before aborting the operation (in ms). Use 0 for no timeout. * @return length (in bytes) of the response, or NFC_ETIMEOUT if timeout delay has expired, * NFC_EOPABORTED if operation has been aborted, NFC_EIO in case of IO failure */ static int pn532_i2c_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t frameBuf[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int frameLength; int TFI_idx; size_t len; frameLength = pn532_i2c_wait_rdyframe(pnd, frameBuf, sizeof(frameBuf), timeout); if (NFC_EOPABORTED == pnd->last_error) { return pn532_i2c_ack(pnd); } if (frameLength < 0) { goto error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(frameBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == frameBuf[3]) && (0xff == frameBuf[4])) { uint8_t errorCode = frameBuf[5]; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Application level error detected (%d)", errorCode); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == frameBuf[3]) && (0xff == frameBuf[4])) { // Extended frame len = (frameBuf[5] << 8) + frameBuf[6]; // Verify length checksum if (((frameBuf[5] + frameBuf[6] + frameBuf[7]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } TFI_idx = 8; } else { // Normal frame len = frameBuf[3]; // Verify length checksum if ((uint8_t)(frameBuf[3] + frameBuf[4])) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } TFI_idx = 5; } if ((len - 2) > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } uint8_t TFI = frameBuf[TFI_idx]; if (TFI != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (frameBuf[TFI_idx + 1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Command Code verification failed. (got %d, expected %d)", frameBuf[TFI_idx + 1], CHIP_DATA(pnd)->last_command + 1); pnd->last_error = NFC_EIO; goto error; } uint8_t DCS = frameBuf[TFI_idx + len]; uint8_t btDCS = DCS; // Compute data checksum for (size_t i = 0; i < len; i++) { btDCS += frameBuf[TFI_idx + i]; } if (btDCS != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Data checksum mismatch (DCS = %02x, btDCS = %d)", DCS, btDCS); pnd->last_error = NFC_EIO; goto error; } if (0x00 != frameBuf[TFI_idx + len + 1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Frame postamble mismatch (got %d)", frameBuf[frameLength - 1]); pnd->last_error = NFC_EIO; goto error; } memcpy(pbtData, &frameBuf[TFI_idx + 2], len - 2); /* The PN53x command is done and we successfully received the reply */ return len - 2; error: return pnd->last_error; } /** * @brief Send an ACK frame to the PN532 device. * * @param pnd pointer on the NFC device. * @return NFC_SUCCESS on success, otherwise an error code */ int pn532_i2c_ack(nfc_device *pnd) { return i2c_write(DRIVER_DATA(pnd)->dev, pn53x_ack_frame, sizeof(pn53x_ack_frame)); } /** * @brief Abort any pending operation * * @param pnd pointer on the NFC device. * @return NFC_SUCCESS */ static int pn532_i2c_abort_command(nfc_device *pnd) { if (pnd) { DRIVER_DATA(pnd)->abort_flag = true; } return NFC_SUCCESS; } const struct pn53x_io pn532_i2c_io = { .send = pn532_i2c_send, .receive = pn532_i2c_receive, }; const struct nfc_driver pn532_i2c_driver = { .name = PN532_I2C_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_i2c_scan, .open = pn532_i2c_open, .close = pn532_i2c_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_i2c_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
zzyjames55-nfc0805
libnfc/drivers/pn532_i2c.c
C
lgpl
18,584
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn53x_usb.c * @brief Driver for PN53x using USB */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H /* Thanks to d18c7db and Okko for example code */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/select.h> #include <errno.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "buses/usbbus.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "drivers/pn53x_usb.h" #define PN53X_USB_DRIVER_NAME "pn53x_usb" #define LOG_CATEGORY "libnfc.driver.pn53x_usb" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define USB_INFINITE_TIMEOUT 0 #define DRIVER_DATA(pnd) ((struct pn53x_usb_data*)(pnd->driver_data)) typedef enum { UNKNOWN, NXP_PN531, SONY_PN531, NXP_PN533, ASK_LOGO, SCM_SCL3711, SONY_RCS360 } pn53x_usb_model; // Internal data struct struct pn53x_usb_data { usb_dev_handle *pudh; pn53x_usb_model model; uint32_t uiEndPointIn; uint32_t uiEndPointOut; uint32_t uiMaxPacketSize; volatile bool abort_flag; }; // Internal io struct const struct pn53x_io pn53x_usb_io; // Prototypes bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len); int pn53x_usb_init(nfc_device *pnd); static int pn53x_usb_bulk_read(struct pn53x_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) { int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); if (res > 0) { LOG_HEX(NFC_LOG_GROUP_COM, "RX", abtRx, res); } else if (res < 0) { if (res != -USB_TIMEDOUT) log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res)); } return res; } static int pn53x_usb_bulk_write(struct pn53x_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) { LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTx, szTx); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); if (res > 0) { // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details if ((res % data->uiMaxPacketSize) == 0) { usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout); } } else { log_put(NFC_LOG_GROUP_COM, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res)); } return res; } struct pn53x_usb_supported_device { uint16_t vendor_id; uint16_t product_id; pn53x_usb_model model; const char *name; }; const struct pn53x_usb_supported_device pn53x_usb_supported_devices[] = { { 0x04CC, 0x0531, NXP_PN531, "Philips / PN531" }, { 0x04CC, 0x2533, NXP_PN533, "NXP / PN533" }, { 0x04E6, 0x5591, SCM_SCL3711, "SCM Micro / SCL3711-NFC&RW" }, { 0x054c, 0x0193, SONY_PN531, "Sony / PN531" }, { 0x1FD3, 0x0608, ASK_LOGO, "ASK / LoGO" }, { 0x054C, 0x02E1, SONY_RCS360, "Sony / FeliCa S360 [PaSoRi]" } }; static pn53x_usb_model pn53x_usb_get_device_model(uint16_t vendor_id, uint16_t product_id) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((vendor_id == pn53x_usb_supported_devices[n].vendor_id) && (product_id == pn53x_usb_supported_devices[n].product_id)) return pn53x_usb_supported_devices[n].model; } return UNKNOWN; } int pn53x_usb_ack(nfc_device *pnd); // Find transfer endpoints for bulk transfers static void pn53x_usb_get_end_points(struct usb_device *dev, struct pn53x_usb_data *data) { uint32_t uiIndex; uint32_t uiEndPoint; struct usb_interface_descriptor *puid = dev->config->interface->altsetting; // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) { // Only accept bulk transfer endpoints (ignore interrupt endpoints) if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK) continue; // Copy the endpoint to a local var, makes it more readable code uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress; // Test if we dealing with a bulk IN endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) { data->uiEndPointIn = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } // Test if we dealing with a bulk OUT endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) { data->uiEndPointOut = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } } } static size_t pn53x_usb_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void)context; usb_prepare(); size_t device_found = 0; uint32_t uiBusIndex = 0; struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { // Make sure there are 2 endpoints available // with libusb-win32 we got some null pointers so be robust before looking at endpoints: if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) { // Nope, we maybe want the next one, let's try to find another continue; } if (dev->config->interface->altsetting->bNumEndpoints < 2) { // Nope, we maybe want the next one, let's try to find another continue; } usb_dev_handle *udev = usb_open(dev); if (udev == NULL) continue; // Set configuration int res = usb_set_configuration(udev, 1); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res)); usb_close(udev); // we failed to use the device continue; } // pn53x_usb_get_usb_device_name (dev, udev, pnddDevices[device_found].acDevice, sizeof (pnddDevices[device_found].acDevice)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "device found: Bus %s Device %s", bus->dirname, dev->filename); usb_close(udev); snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s:%s", PN53X_USB_DRIVER_NAME, bus->dirname, dev->filename); device_found++; // Test if we reach the maximum "wanted" devices if (device_found == connstrings_len) { return device_found; } } } } } return device_found; } struct pn53x_usb_descriptor { char *dirname; char *filename; }; bool pn53x_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) { *buffer = '\0'; if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (udev) { usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len); if (strlen(buffer) > 0) strcpy(buffer + strlen(buffer), " / "); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer)); } } if (!*buffer) { for (size_t n = 0; n < sizeof(pn53x_usb_supported_devices) / sizeof(struct pn53x_usb_supported_device); n++) { if ((pn53x_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (pn53x_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { strncpy(buffer, pn53x_usb_supported_devices[n].name, len); buffer[len - 1] = '\0'; return true; } } } return false; } static nfc_device * pn53x_usb_open(const nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; struct pn53x_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = connstring_decode(connstring, PN53X_USB_DRIVER_NAME, "usb", &desc.dirname, &desc.filename); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { goto free_mem; } struct pn53x_usb_data data = { .pudh = NULL, .uiEndPointIn = 0, .uiEndPointOut = 0, }; struct usb_bus *bus; struct usb_device *dev; usb_prepare(); for (bus = usb_get_busses(); bus; bus = bus->next) { if (connstring_decode_level > 1) { // A specific bus have been specified if (0 != strcmp(bus->dirname, desc.dirname)) continue; } for (dev = bus->devices; dev; dev = dev->next) { if (connstring_decode_level > 2) { // A specific dev have been specified if (0 != strcmp(dev->filename, desc.filename)) continue; } // Open the USB device if ((data.pudh = usb_open(dev)) == NULL) continue; // Retrieve end points pn53x_usb_get_end_points(dev, &data); // Set configuration int res = usb_set_configuration(data.pudh, 1); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set USB configuration (%s)", _usb_strerror(res)); if (EPERM == -res) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: Please double check USB permissions for device %04x:%04x", dev->descriptor.idVendor, dev->descriptor.idProduct); } usb_close(data.pudh); // we failed to use the specified device goto free_mem; } res = usb_claim_interface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } data.model = pn53x_usb_get_device_model(dev->descriptor.idVendor, dev->descriptor.idProduct); // Allocate memory for the device info and specification, fill it and return the info pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); goto error; } pn53x_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name)); pnd->driver_data = malloc(sizeof(struct pn53x_usb_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } *DRIVER_DATA(pnd) = data; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn53x_usb_io) == NULL) { perror("malloc"); goto error; } switch (DRIVER_DATA(pnd)->model) { // empirical tuning case ASK_LOGO: CHIP_DATA(pnd)->timer_correction = 50; break; case SCM_SCL3711: case NXP_PN533: CHIP_DATA(pnd)->timer_correction = 46; break; case NXP_PN531: CHIP_DATA(pnd)->timer_correction = 50; break; case SONY_PN531: CHIP_DATA(pnd)->timer_correction = 54; break; case SONY_RCS360: case UNKNOWN: CHIP_DATA(pnd)->timer_correction = 0; // TODO: allow user to know if timed functions are available break; } pnd->driver = &pn53x_usb_driver; // HACK1: Send first an ACK as Abort command, to reset chip before talking to it: pn53x_usb_ack(pnd); // HACK2: Then send a GetFirmware command to resync USB toggle bit between host & device // in case host used set_configuration and expects the device to have reset its toggle bit, which PN53x doesn't do if (pn53x_usb_init(pnd) < 0) { usb_close(data.pudh); goto error; } DRIVER_DATA(pnd)->abort_flag = false; goto free_mem; } } // We ran out of devices before the index required goto free_mem; error: // Free allocated structure on error. nfc_device_free(pnd); pnd = NULL; free_mem: free(desc.dirname); free(desc.filename); return pnd; } static void pn53x_usb_close(nfc_device *pnd) { pn53x_usb_ack(pnd); if (DRIVER_DATA(pnd)->model == ASK_LOGO) { /* Set P30, P31, P32, P33, P35 to logic 1 and P34 to 0 logic */ /* ie. Switch all LEDs off and turn off progressive field */ pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P32) | _BV(P33) | _BV(P35)); } pn53x_idle(pnd); int res; if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res)); } if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res)); } pn53x_data_free(pnd); nfc_device_free(pnd); } #define PN53X_USB_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn53x_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { uint8_t abtFrame[PN53X_USB_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; int res = 0; pn53x_build_frame(abtFrame, &szFrame, pbtData, szData); if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), abtFrame, szFrame, timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; if ((res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), timeout)) < 0) { // try to interrupt current device state pn53x_usb_ack(pnd); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, res) == 0) { // The PN53x is running the sent command } else { // For some reasons (eg. send another command while a previous one is // running), the PN533 sometimes directly replies the response packet // instead of ACK frame, so we send a NACK frame to force PN533 to resend // response packet. With this hack, the nextly executed function (ie. // pn53x_usb_receive()) will be able to retreive the correct response // packet. // FIXME Sony reader is also affected by this bug but NACK is not supported if ((res = pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *)pn53x_nack_frame, sizeof(pn53x_nack_frame), timeout)) < 0) { pnd->last_error = res; // try to interrupt current device state pn53x_usb_ack(pnd); return pnd->last_error; } } return NFC_SUCCESS; } #define USB_TIMEOUT_PER_PASS 200 static int pn53x_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) { size_t len; off_t offset = 0; uint8_t abtRxBuf[PN53X_USB_BUFFER_LEN]; int res; /* * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS) * timeout to allow breaking the loop if the user wants to stop it. */ int usb_timeout; int remaining_time = timeout; read: if (timeout == USB_INFINITE_TIMEOUT) { usb_timeout = USB_TIMEOUT_PER_PASS; } else { // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism remaining_time -= USB_TIMEOUT_PER_PASS; if (remaining_time <= 0) { pnd->last_error = NFC_ETIMEOUT; return pnd->last_error; } else { usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS); } } res = pn53x_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout); if (res == -USB_TIMEDOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; pn53x_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; } } if (res < 0) { // try to interrupt current device state pn53x_usb_ack(pnd); pnd->last_error = res; return pnd->last_error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; if ((0x01 == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { // Error frame log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; return pnd->last_error; } else if ((0xff == abtRxBuf[offset]) && (0xff == abtRxBuf[offset + 1])) { // Extended frame offset += 2; // (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] (LEN) include TFI + (CC+1) len = (abtRxBuf[offset] << 8) + abtRxBuf[offset + 1] - 2; if (((abtRxBuf[offset] + abtRxBuf[offset + 1] + abtRxBuf[offset + 2]) % 256) != 0) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; } else { // Normal frame if (256 != (abtRxBuf[offset] + abtRxBuf[offset + 1])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[offset] - 2; offset += 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; return pnd->last_error; } // TFI + PD0 (CC+1) if (abtRxBuf[offset] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; memcpy(pbtData, abtRxBuf + offset, len); offset += len; uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[offset]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (0x00 != abtRxBuf[offset]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // The PN53x command is done and we successfully received the reply pnd->last_error = 0; return len; } int pn53x_usb_ack(nfc_device *pnd) { return pn53x_usb_bulk_write(DRIVER_DATA(pnd), (uint8_t *) pn53x_ack_frame, sizeof(pn53x_ack_frame), 1000); } int pn53x_usb_init(nfc_device *pnd) { int res = 0; // Sometimes PN53x USB doesn't reply ACK one the first frame, so we need to send a dummy one... //pn53x_check_communication (pnd); // Sony RC-S360 doesn't support this command for now so let's use a get_firmware_version instead: const uint8_t abtCmd[] = { GetFirmwareVersion }; pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); // ...and we don't care about error pnd->last_error = 0; if (SONY_RCS360 == DRIVER_DATA(pnd)->model) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "SONY RC-S360 initialization."); const uint8_t abtCmd2[] = { 0x18, 0x01 }; pn53x_transceive(pnd, abtCmd2, sizeof(abtCmd2), NULL, 0, -1); pn53x_usb_ack(pnd); } if ((res = pn53x_init(pnd)) < 0) return res; if (ASK_LOGO == DRIVER_DATA(pnd)->model) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ASK LoGO initialization."); /* Internal registers */ /* Disable 100mA current limit, Power on Secure IC (SVDD) */ pn53x_write_register(pnd, PN53X_REG_Control_switch_rng, 0xFF, SYMBOL_CURLIMOFF | SYMBOL_SIC_SWITCH_EN | SYMBOL_RANDOM_DATAREADY); /* Select the signal to be output on SIGOUT: Modulation signal (envelope) from the internal coder */ pn53x_write_register(pnd, PN53X_REG_CIU_TxSel, 0xFF, 0x14); /* SFR Registers */ /* Setup push-pulls for pins from P30 to P35 */ pn53x_write_register(pnd, PN53X_SFR_P3CFGB, 0xFF, 0x37); /* On ASK LoGO hardware: LEDs port bits definition: * LED 1: bit 2 (P32) * LED 2: bit 1 (P31) * LED 3: bit 0 or 3 (depending of hardware revision) (P30 or P33) * LED 4: bit 5 (P35) Notes: * Set logical 0 to switch LED on; logical 1 to switch LED off. * Bit 4 should be maintained at 1 to keep RF field on. Progressive field activation: The ASK LoGO hardware can progressively power-up the antenna. To use this feature we have to switch on the field by switching on the field on PN533 (RFConfiguration) then set P34 to '1', and cut-off the field by switching off the field on PN533 then set P34 to '0'. */ /* Set P30, P31, P33, P35 to logic 1 and P32, P34 to 0 logic */ /* ie. Switch LED1 on and turn off progressive field */ pn53x_write_register(pnd, PN53X_SFR_P3, 0xFF, _BV(P30) | _BV(P31) | _BV(P33) | _BV(P35)); } return NFC_SUCCESS; } static int pn53x_usb_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable) { int res = 0; if ((res = pn53x_set_property_bool(pnd, property, bEnable)) < 0) return res; switch (DRIVER_DATA(pnd)->model) { case ASK_LOGO: if (NP_ACTIVATE_FIELD == property) { /* Switch on/off LED2 and Progressive Field GPIO according to ACTIVATE_FIELD option */ log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Switch progressive field %s", bEnable ? "On" : "Off"); if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P31) | _BV(P34), bEnable ? _BV(P34) : _BV(P31))) < 0) return NFC_ECHIP; } break; case SCM_SCL3711: if (NP_ACTIVATE_FIELD == property) { // Switch on/off LED according to ACTIVATE_FIELD option if ((res = pn53x_write_register(pnd, PN53X_SFR_P3, _BV(P32), bEnable ? 0 : _BV(P32))) < 0) return res; } break; case NXP_PN531: case NXP_PN533: case SONY_PN531: case SONY_RCS360: case UNKNOWN: // Nothing to do. break; } return NFC_SUCCESS; } static int pn53x_usb_abort_command(nfc_device *pnd) { DRIVER_DATA(pnd)->abort_flag = true; return NFC_SUCCESS; } const struct pn53x_io pn53x_usb_io = { .send = pn53x_usb_send, .receive = pn53x_usb_receive, }; const struct nfc_driver pn53x_usb_driver = { .name = PN53X_USB_DRIVER_NAME, .scan_type = NOT_INTRUSIVE, .scan = pn53x_usb_scan, .open = pn53x_usb_open, .close = pn53x_usb_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_usb_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn53x_usb_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
zzyjames55-nfc0805
libnfc/drivers/pn53x_usb.c
C
lgpl
25,937
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tarti?re * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Laurent Latil * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_i2c.h * @brief Driver for PN532 connected through I2C bus */ #ifndef __NFC_DRIVER_PN532_I2C_H__ #define __NFC_DRIVER_PN532_I2C_H__ #include <nfc/nfc-types.h> /* Reference to the I2C driver structure */ extern const struct nfc_driver pn532_i2c_driver; #endif // ! __NFC_DRIVER_I2C_H__
zzyjames55-nfc0805
libnfc/drivers/pn532_i2c.h
C
lgpl
1,431
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file arygon.h * @brief Driver for PN53x-equipped ARYGON device connected using UART */ #ifndef __NFC_DRIVER_ARYGON_H__ #define __NFC_DRIVER_ARYGON_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver arygon_driver; #endif // ! __NFC_DRIVER_ARYGON_H__
zzyjames55-nfc0805
libnfc/drivers/arygon.h
C
lgpl
1,356
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122_pcsc.c * @brief Driver for ACR122 devices (e.g. Tikitag, Touchatag, ACS ACR122) behind PC/SC */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <nfc/nfc.h> #include "chips/pn53x.h" #include "drivers/acr122_pcsc.h" #include "nfc-internal.h" // Bus #ifdef __APPLE__ #include <PCSC/winscard.h> #include <PCSC/wintypes.h> #else #include <winscard.h> #endif #define ACR122_PCSC_DRIVER_NAME "acr122_pcsc" #if defined (_WIN32) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(3500) #elif defined(__APPLE__) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) #elif defined (__FreeBSD__) || defined (__OpenBSD__) # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE (((0x31) << 16) | ((3500) << 2)) #elif defined (__linux__) # include <reader.h> // Escape IOCTL tested successfully: # define IOCTL_CCID_ESCAPE_SCARD_CTL_CODE SCARD_CTL_CODE(1) #else # error "Can't determine serial string for your system" #endif #include <nfc/nfc.h> #define SCARD_OPERATION_SUCCESS 0x61 #define SCARD_OPERATION_ERROR 0x63 #ifndef SCARD_PROTOCOL_UNDEFINED # define SCARD_PROTOCOL_UNDEFINED SCARD_PROTOCOL_UNSET #endif #define FIRMWARE_TEXT "ACR122U" // Tested on: ACR122U101(ACS), ACR122U102(Tikitag), ACR122U203(ACS) #define ACR122_PCSC_WRAP_LEN 5 #define ACR122_PCSC_COMMAND_LEN 266 #define ACR122_PCSC_RESPONSE_LEN 268 #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define LOG_CATEGORY "libnfc.driver.acr122_pcsc" // Internal data struct const struct pn53x_io acr122_pcsc_io; // Prototypes char *acr122_pcsc_firmware(nfc_device *pnd); const char *supported_devices[] = { "ACS ACR122", // ACR122U & Touchatag, last version "ACS ACR 38U-CCID", // Touchatag, early version "ACS ACR38U-CCID", // Touchatag, early version, under MacOSX "ACS AET65", // Touchatag using CCID driver version >= 1.4.6 " CCID USB", // ?? NULL }; struct acr122_pcsc_data { SCARDHANDLE hCard; SCARD_IO_REQUEST ioCard; uint8_t abtRx[ACR122_PCSC_RESPONSE_LEN]; size_t szRx; }; #define DRIVER_DATA(pnd) ((struct acr122_pcsc_data*)(pnd->driver_data)) static SCARDCONTEXT _SCardContext; static int _iSCardContextRefCount = 0; static SCARDCONTEXT * acr122_pcsc_get_scardcontext(void) { if (_iSCardContextRefCount == 0) { if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &_SCardContext) != SCARD_S_SUCCESS) return NULL; } _iSCardContextRefCount++; return &_SCardContext; } static void acr122_pcsc_free_scardcontext(void) { if (_iSCardContextRefCount) { _iSCardContextRefCount--; if (!_iSCardContextRefCount) { SCardReleaseContext(_SCardContext); } } } #define PCSC_MAX_DEVICES 16 /** * @brief List opened devices * * Probe PCSC to find ACR122 devices (ACR122U and Touchatag/Tikitag). * * @param connstring array of nfc_connstring where found device's connection strings will be stored. * @param connstrings_len size of connstrings array. * @return number of devices found. */ static size_t acr122_pcsc_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void) context; size_t szPos = 0; char acDeviceNames[256 + 64 * PCSC_MAX_DEVICES]; size_t szDeviceNamesLen = sizeof(acDeviceNames); SCARDCONTEXT *pscc; int i; // Clear the reader list memset(acDeviceNames, '\0', szDeviceNamesLen); // Test if context succeeded if (!(pscc = acr122_pcsc_get_scardcontext())) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: %s", "PCSC context not found (make sure PCSC daemon is running)."); return 0; } // Retrieve the string array of all available pcsc readers DWORD dwDeviceNamesLen = szDeviceNamesLen; if (SCardListReaders(*pscc, NULL, acDeviceNames, &dwDeviceNamesLen) != SCARD_S_SUCCESS) return 0; size_t device_found = 0; while ((acDeviceNames[szPos] != '\0') && (device_found < connstrings_len)) { bool bSupported = false; for (i = 0; supported_devices[i] && !bSupported; i++) { int l = strlen(supported_devices[i]); bSupported = 0 == strncmp(supported_devices[i], acDeviceNames + szPos, l); } if (bSupported) { // Supported ACR122 device found snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s", ACR122_PCSC_DRIVER_NAME, acDeviceNames + szPos); device_found++; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "PCSC device [%s] is not NFC capable or not supported by libnfc.", acDeviceNames + szPos); } // Find next device name position while (acDeviceNames[szPos++] != '\0'); } acr122_pcsc_free_scardcontext(); return device_found; } struct acr122_pcsc_descriptor { char *pcsc_device_name; }; static nfc_device * acr122_pcsc_open(const nfc_context *context, const nfc_connstring connstring) { struct acr122_pcsc_descriptor ndd; int connstring_decode_level = connstring_decode(connstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 1) { return NULL; } nfc_connstring fullconnstring; if (connstring_decode_level == 1) { // Device was not specified, take the first one we can find size_t szDeviceFound = acr122_pcsc_scan(context, &fullconnstring, 1); if (szDeviceFound < 1) return NULL; connstring_decode_level = connstring_decode(fullconnstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 2) { return NULL; } } else { memcpy(fullconnstring, connstring, sizeof(nfc_connstring)); } if (strlen(ndd.pcsc_device_name) < 5) { // We can assume it's a reader ID as pcsc_name always ends with "NN NN" // Device was not specified, only ID, retrieve it size_t index; if (sscanf(ndd.pcsc_device_name, "%4" SCNuPTR, &index) != 1) { free(ndd.pcsc_device_name); return NULL; } nfc_connstring *ncs = malloc(sizeof(nfc_connstring) * (index + 1)); if (!ncs) { perror("malloc"); free(ndd.pcsc_device_name); return NULL; } size_t szDeviceFound = acr122_pcsc_scan(context, ncs, index + 1); if (szDeviceFound < index + 1) { free(ncs); free(ndd.pcsc_device_name); return NULL; } strncpy(fullconnstring, ncs[index], sizeof(nfc_connstring)); fullconnstring[sizeof(nfc_connstring) - 1] = '\0'; free(ncs); connstring_decode_level = connstring_decode(fullconnstring, ACR122_PCSC_DRIVER_NAME, "pcsc", &ndd.pcsc_device_name, NULL); if (connstring_decode_level < 2) { free(ndd.pcsc_device_name); return NULL; } } char *pcFirmware; nfc_device *pnd = nfc_device_new(context, fullconnstring); if (!pnd) { perror("malloc"); goto error; } pnd->driver_data = malloc(sizeof(struct acr122_pcsc_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } // Alloc and init chip's data if (pn53x_data_new(pnd, &acr122_pcsc_io) == NULL) { perror("malloc"); goto error; } SCARDCONTEXT *pscc; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open %s", ndd.pcsc_device_name); // Test if context succeeded if (!(pscc = acr122_pcsc_get_scardcontext())) goto error; // Test if we were able to connect to the "emulator" card if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_EXCLUSIVE, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { // Connect to ACR122 firmware version >2.0 if (SCardConnect(*pscc, ndd.pcsc_device_name, SCARD_SHARE_DIRECT, 0, &(DRIVER_DATA(pnd)->hCard), (void *) & (DRIVER_DATA(pnd)->ioCard.dwProtocol)) != SCARD_S_SUCCESS) { // We can not connect to this device. log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PCSC connect failed"); goto error; } } // Configure I/O settings for card communication DRIVER_DATA(pnd)->ioCard.cbPciLength = sizeof(SCARD_IO_REQUEST); // Retrieve the current firmware version pcFirmware = acr122_pcsc_firmware(pnd); if (strstr(pcFirmware, FIRMWARE_TEXT) != NULL) { // Done, we found the reader we are looking for snprintf(pnd->name, sizeof(pnd->name), "%s / %s", ndd.pcsc_device_name, pcFirmware); // 50: empirical tuning on Touchatag // 46: empirical tuning on ACR122U CHIP_DATA(pnd)->timer_correction = 50; pnd->driver = &acr122_pcsc_driver; pn53x_init(pnd); free(ndd.pcsc_device_name); return pnd; } error: free(ndd.pcsc_device_name); nfc_device_free(pnd); return NULL; } static void acr122_pcsc_close(nfc_device *pnd) { pn53x_idle(pnd); SCardDisconnect(DRIVER_DATA(pnd)->hCard, SCARD_LEAVE_CARD); acr122_pcsc_free_scardcontext(); pn53x_data_free(pnd); nfc_device_free(pnd); } static int acr122_pcsc_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { // FIXME: timeout is not handled (void) timeout; // Make sure the command does not overflow the send buffer if (szData > ACR122_PCSC_COMMAND_LEN) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Prepare and transmit the send buffer const size_t szTxBuf = szData + 6; uint8_t abtTxBuf[ACR122_PCSC_WRAP_LEN + ACR122_PCSC_COMMAND_LEN] = { 0xFF, 0x00, 0x00, 0x00, szData + 1, 0xD4 }; memcpy(abtTxBuf + 6, pbtData, szData); LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTxBuf, szTxBuf); DRIVER_DATA(pnd)->szRx = 0; DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx); if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { /* * In this communication mode, we directly have the response from the * PN532. Save it in the driver data structure so that it can be retrieved * in ac122_receive(). * * Some devices will never enter this state (e.g. Touchatag) but are still * supported through SCardTransmit calls (see bellow). * * This state is generaly reached when the ACR122 has no target in it's * field. */ if (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtTxBuf, szTxBuf, DRIVER_DATA(pnd)->abtRx, ACR122_PCSC_RESPONSE_LEN, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } } else { /* * In T=0 mode, we receive an acknoledge from the MCU, in T=1 mode, we * receive the response from the PN532. */ if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtTxBuf, szTxBuf, NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } } if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { /* * Check the MCU response */ // Make sure we received the byte-count we expected if (dwRxLen != 2) { pnd->last_error = NFC_EIO; return pnd->last_error; } // Check if the operation was successful, so an answer is available if (DRIVER_DATA(pnd)->abtRx[0] == SCARD_OPERATION_ERROR) { pnd->last_error = NFC_EIO; return pnd->last_error; } } else { DRIVER_DATA(pnd)->szRx = dwRxLen; } return NFC_SUCCESS; } static int acr122_pcsc_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szData, int timeout) { // FIXME: timeout is not handled (void) timeout; int len; uint8_t abtRxCmd[5] = { 0xFF, 0xC0, 0x00, 0x00 }; if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_T0) { /* * Retrieve the PN532 response. */ DWORD dwRxLen = sizeof(DRIVER_DATA(pnd)->abtRx); abtRxCmd[4] = DRIVER_DATA(pnd)->abtRx[1]; if (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtRxCmd, sizeof(abtRxCmd), NULL, DRIVER_DATA(pnd)->abtRx, &dwRxLen) != SCARD_S_SUCCESS) { pnd->last_error = NFC_EIO; return pnd->last_error; } DRIVER_DATA(pnd)->szRx = dwRxLen; } else { /* * We already have the PN532 answer, it was saved by acr122_pcsc_send(). */ } LOG_HEX(NFC_LOG_GROUP_COM, "RX", DRIVER_DATA(pnd)->abtRx, DRIVER_DATA(pnd)->szRx); // Make sure we have an emulated answer that fits the return buffer if (DRIVER_DATA(pnd)->szRx < 4 || (DRIVER_DATA(pnd)->szRx - 4) > szData) { pnd->last_error = NFC_EIO; return pnd->last_error; } // Wipe out the 4 APDU emulation bytes: D5 4B .. .. .. 90 00 len = DRIVER_DATA(pnd)->szRx - 4; memcpy(pbtData, DRIVER_DATA(pnd)->abtRx + 2, len); return len; } char * acr122_pcsc_firmware(nfc_device *pnd) { uint8_t abtGetFw[5] = { 0xFF, 0x00, 0x48, 0x00, 0x00 }; uint32_t uiResult; static char abtFw[11]; DWORD dwFwLen = sizeof(abtFw); memset(abtFw, 0x00, sizeof(abtFw)); if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { uiResult = SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtGetFw, sizeof(abtGetFw), (uint8_t *) abtFw, dwFwLen - 1, &dwFwLen); } else { uiResult = SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtGetFw, sizeof(abtGetFw), NULL, (uint8_t *) abtFw, &dwFwLen); } if (uiResult != SCARD_S_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "No ACR122 firmware received, Error: %08x", uiResult); } return abtFw; } #if 0 bool acr122_pcsc_led_red(nfc_device *pnd, bool bOn) { uint8_t abtLed[9] = { 0xFF, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x00 }; uint8_t abtBuf[2]; DWORD dwBufLen = sizeof(abtBuf); (void) bOn; if (DRIVER_DATA(pnd)->ioCard.dwProtocol == SCARD_PROTOCOL_UNDEFINED) { return (SCardControl(DRIVER_DATA(pnd)->hCard, IOCTL_CCID_ESCAPE_SCARD_CTL_CODE, abtLed, sizeof(abtLed), abtBuf, dwBufLen, &dwBufLen) == SCARD_S_SUCCESS); } else { return (SCardTransmit(DRIVER_DATA(pnd)->hCard, &(DRIVER_DATA(pnd)->ioCard), abtLed, sizeof(abtLed), NULL, abtBuf, &dwBufLen) == SCARD_S_SUCCESS); } } #endif const struct pn53x_io acr122_pcsc_io = { .send = acr122_pcsc_send, .receive = acr122_pcsc_receive, }; const struct nfc_driver acr122_pcsc_driver = { .name = ACR122_PCSC_DRIVER_NAME, .scan = acr122_pcsc_scan, .open = acr122_pcsc_open, .close = acr122_pcsc_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = NULL, // Abort is not supported in this driver .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
zzyjames55-nfc0805
libnfc/drivers/acr122_pcsc.c
C
lgpl
17,141
# set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) noinst_LTLIBRARIES = libnfcdrivers.la libnfcdrivers_la_SOURCES = libnfcdrivers_la_CFLAGS = @DRIVERS_CFLAGS@ -I$(top_srcdir)/libnfc -I$(top_srcdir)/libnfc/buses libnfcdrivers_la_LIBADD = if DRIVER_ACR122_PCSC_ENABLED libnfcdrivers_la_SOURCES += acr122_pcsc.c acr122_pcsc.h endif if DRIVER_ACR122_USB_ENABLED libnfcdrivers_la_SOURCES += acr122_usb.c acr122_usb.h endif if DRIVER_ACR122S_ENABLED libnfcdrivers_la_SOURCES += acr122s.c acr122s.h endif if DRIVER_ARYGON_ENABLED libnfcdrivers_la_SOURCES += arygon.c arygon.h endif if DRIVER_PN53X_USB_ENABLED libnfcdrivers_la_SOURCES += pn53x_usb.c pn53x_usb.h endif if DRIVER_PN532_UART_ENABLED libnfcdrivers_la_SOURCES += pn532_uart.c pn532_uart.h endif if DRIVER_PN532_SPI_ENABLED libnfcdrivers_la_SOURCES += pn532_spi.c pn532_spi.h endif if DRIVER_PN532_I2C_ENABLED libnfcdrivers_la_SOURCES += pn532_i2c.c pn532_i2c.h endif if PCSC_ENABLED libnfcdrivers_la_CFLAGS += @libpcsclite_CFLAGS@ libnfcdrivers_la_LIBADD += @libpcsclite_LIBS@ endif if LIBUSB_ENABLED libnfcdrivers_la_CFLAGS += @libusb_CFLAGS@ libnfcdrivers_la_LIBADD += @libusb_LIBS@ endif
zzyjames55-nfc0805
libnfc/drivers/Makefile.am
Makefile
lgpl
1,206
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Evgeny Boger * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_spi.h * @brief Driver for PN532 connected in SPI */ #ifndef __NFC_DRIVER_PN532_SPI_H__ #define __NFC_DRIVER_PN532_SPI_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn532_spi_driver; #endif // ! __NFC_DRIVER_PN532_SPI_H__
zzyjames55-nfc0805
libnfc/drivers/pn532_spi.h
C
lgpl
1,384
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_uart.c * @brief PN532 driver using UART bus (UART, RS232, etc.) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_uart.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" #define PN532_UART_DEFAULT_SPEED 115200 #define PN532_UART_DRIVER_NAME "pn532_uart" #define LOG_CATEGORY "libnfc.driver.pn532_uart" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // Internal data structs const struct pn53x_io pn532_uart_io; struct pn532_uart_data { serial_port port; #ifndef WIN32 int iAbortFds[2]; #else volatile bool abort_flag; #endif }; // Prototypes int pn532_uart_ack(nfc_device *pnd); int pn532_uart_wakeup(nfc_device *pnd); #define DRIVER_DATA(pnd) ((struct pn532_uart_data*)(pnd->driver_data)) static size_t pn532_uart_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on serial port: %s at %d bauds.", acPort, PN532_UART_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp); // Serial port claimed but we need to check if a PN532_UART is opened. uart_set_speed(sp, PN532_UART_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_UART_DRIVER_NAME, acPort, PN532_UART_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); return 0; } pnd->driver = &pn532_uart_driver; pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_uart_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct pn532_uart_descriptor { char *port; uint32_t speed; }; static void pn532_uart_close(nfc_device *pnd) { pn53x_idle(pnd); // Release UART port uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * pn532_uart_open(const nfc_context *context, const nfc_connstring connstring) { struct pn532_uart_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, PN532_UART_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = PN532_UART_DEFAULT_SPEED; } serial_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); if (sp == CLAIMED_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) { free(ndd.port); return NULL; } // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp); uart_set_speed(sp, ndd.speed); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_UART_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct pn532_uart_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_uart_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_uart_driver; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { nfc_perror(pnd, "pn53x_check_communication"); pn532_uart_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } int pn532_uart_wakeup(nfc_device *pnd) { /* High Speed Unit (HSU) wake up consist to send 0x55 and wait a "long" delay for PN532 being wakeup. */ const uint8_t pn532_wakeup_preamble[] = { 0x55, 0x55, 0x00, 0x00, 0x00 }; int res = uart_send(DRIVER_DATA(pnd)->port, pn532_wakeup_preamble, sizeof(pn532_wakeup_preamble), 0); CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 should now be awake return res; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn532_uart_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Before sending anything, we need to discard from any junk bytes uart_flush_input(DRIVER_DATA(pnd)->port); switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN] = { 0x00, 0x00, 0xff }; // Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame, timeout); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, sizeof(abtRxBuf), 0, timeout); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } static int pn532_uart_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; void *abort_p = NULL; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]); #else abort_p = (void *) & (DRIVER_DATA(pnd)->abort_flag); #endif pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { pn532_uart_ack(pnd); return NFC_EOPABORTED; } if (pnd->last_error < 0) { goto error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Error frame uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Extended frame pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } // (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1) len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2; if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } } else { // Normal frame if (256 != (abtRxBuf[3] + abtRxBuf[4])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[3] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } // TFI + PD0 (CC+1) pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; goto error; } if (len) { pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } } pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; goto error; } // The PN53x command is done and we successfully received the reply return len; error: uart_flush_input(DRIVER_DATA(pnd)->port); return pnd->last_error; } int pn532_uart_ack(nfc_device *pnd) { if (POWERDOWN == CHIP_DATA(pnd)->power_mode) { int res = 0; if ((res = pn532_uart_wakeup(pnd)) < 0) { return res; } } return (uart_send(DRIVER_DATA(pnd)->port, pn53x_ack_frame, sizeof(pn53x_ack_frame), 0)); } static int pn532_uart_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->iAbortFds[0]); if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io pn532_uart_io = { .send = pn532_uart_send, .receive = pn532_uart_receive, }; const struct nfc_driver pn532_uart_driver = { .name = PN532_UART_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_uart_scan, .open = pn532_uart_open, .close = pn532_uart_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_uart_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
zzyjames55-nfc0805
libnfc/drivers/pn532_uart.c
C
lgpl
17,165
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_uart.h * @brief Driver for PN532 connected in UART (HSU) */ #ifndef __NFC_DRIVER_PN532_UART_H__ #define __NFC_DRIVER_PN532_UART_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn532_uart_driver; #endif // ! __NFC_DRIVER_PN532_UART_H__
zzyjames55-nfc0805
libnfc/drivers/pn532_uart.h
C
lgpl
1,356
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Evgeny Boger * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn532_spi.c * @brief PN532 driver using SPI bus */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "pn532_spi.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "spi.h" #define PN532_SPI_DEFAULT_SPEED 1000000 // 1 MHz #define PN532_SPI_DRIVER_NAME "pn532_spi" #define PN532_SPI_MODE SPI_MODE_0 #define LOG_CATEGORY "libnfc.driver.pn532_spi" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #ifndef _WIN32 // Needed by sleep() under Unix # include <unistd.h> # include <time.h> # define msleep(x) do { \ struct timespec xsleep; \ xsleep.tv_sec = x / 1000; \ xsleep.tv_nsec = (x - xsleep.tv_sec * 1000) * 1000 * 1000; \ nanosleep(&xsleep, NULL); \ } while (0) #else // Needed by Sleep() under Windows # include <winbase.h> # define msleep Sleep #endif // Internal data structs const struct pn53x_io pn532_spi_io; struct pn532_spi_data { spi_port port; volatile bool abort_flag; }; static const uint8_t pn532_spi_cmd_dataread = 0x03; static const uint8_t pn532_spi_cmd_datawrite = 0x01; // Prototypes int pn532_spi_ack(nfc_device *pnd); int pn532_spi_wakeup(nfc_device *pnd); #define DRIVER_DATA(pnd) ((struct pn532_spi_data*)(pnd->driver_data)) static size_t pn532_spi_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; spi_port sp; char **acPorts = spi_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = spi_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find PN532 device on SPI port: %s at %d Hz.", acPort, PN532_SPI_DEFAULT_SPEED); if ((sp != INVALID_SPI_PORT) && (sp != CLAIMED_SPI_PORT)) { // Serial port claimed but we need to check if a PN532_SPI is opened. spi_set_speed(sp, PN532_SPI_DEFAULT_SPEED); spi_set_mode(sp, PN532_SPI_MODE); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, PN532_SPI_DRIVER_NAME, acPort, PN532_SPI_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); spi_close(sp); return 0; } pnd->driver = &pn532_spi_driver; pnd->driver_data = malloc(sizeof(struct pn532_spi_data)); if (!pnd->driver_data) { perror("malloc"); spi_close(sp); nfc_device_free(pnd); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_spi_io) == NULL) { perror("malloc"); spi_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return 0; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat power mode CHIP_DATA(pnd)->power_mode = LOWVBAT; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) int res = pn53x_check_communication(pnd); spi_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct pn532_spi_descriptor { char *port; uint32_t speed; }; static void pn532_spi_close(nfc_device *pnd) { pn53x_idle(pnd); // Release SPI port spi_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * pn532_spi_open(const nfc_context *context, const nfc_connstring connstring) { struct pn532_spi_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, PN532_SPI_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = PN532_SPI_DEFAULT_SPEED; } spi_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d Hz.", ndd.port, ndd.speed); sp = spi_open(ndd.port); if (sp == INVALID_SPI_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid SPI port: %s", ndd.port); if (sp == CLAIMED_SPI_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "SPI port already claimed: %s", ndd.port); if ((sp == CLAIMED_SPI_PORT) || (sp == INVALID_SPI_PORT)) { free(ndd.port); return NULL; } spi_set_speed(sp, ndd.speed); spi_set_mode(sp, PN532_SPI_MODE); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); spi_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", PN532_SPI_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct pn532_spi_data)); if (!pnd->driver_data) { perror("malloc"); spi_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &pn532_spi_io) == NULL) { perror("malloc"); spi_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // SAMConfiguration command if needed to wakeup the chip and pn53x_SAMConfiguration check if the chip is a PN532 CHIP_DATA(pnd)->type = PN532; // This device starts in LowVBat mode CHIP_DATA(pnd)->power_mode = LOWVBAT; // empirical tuning CHIP_DATA(pnd)->timer_correction = 48; pnd->driver = &pn532_spi_driver; DRIVER_DATA(pnd)->abort_flag = false; // Check communication using "Diagnose" command, with "Communication test" (0x00) if (pn53x_check_communication(pnd) < 0) { nfc_perror(pnd, "pn53x_check_communication"); pn532_spi_close(pnd); return NULL; } pn53x_init(pnd); return pnd; } static int pn532_spi_read_spi_status(nfc_device *pnd) { static const uint8_t pn532_spi_statread_cmd = 0x02; uint8_t spi_status = 0; int res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_statread_cmd, 1, &spi_status, 1, true); if (res != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read SPI status"); return res; } return spi_status; } int pn532_spi_wakeup(nfc_device *pnd) { /* SPI wakeup is basically activating chipselect for several ms. * To do so, we are sending harmless command at very low speed */ int res; const uint32_t prev_port_speed = spi_get_speed(DRIVER_DATA(pnd)->port); // Try to get byte from the SPI line. If PN532 is powered down, the byte will be 0xff (MISO line is high) uint8_t spi_byte = 0; res = spi_receive(DRIVER_DATA(pnd)->port, &spi_byte, 1, true); if (res != NFC_SUCCESS) { return res; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Got %x byte from SPI line before wakeup", spi_byte); CHIP_DATA(pnd)->power_mode = NORMAL; // PN532 will be awake soon msleep(1); if (spi_byte == 0xff) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Wakeup is needed"); spi_set_speed(DRIVER_DATA(pnd)->port, 5000); // set slow speed res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000); // wakeup by sending SAMConfiguration, which works just fine spi_set_speed(DRIVER_DATA(pnd)->port, prev_port_speed); } return res; } #define PN532_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int pn532_spi_wait_for_data(nfc_device *pnd, int timeout) { static const uint8_t pn532_spi_ready = 0x01; static const int pn532_spi_poll_interval = 10; //ms int timer = 0; int ret; while ((ret = pn532_spi_read_spi_status(pnd)) != pn532_spi_ready) { if (ret < 0) { return ret; } if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; return NFC_EOPABORTED; } if (timeout > 0) { timer += pn532_spi_poll_interval; if (timer > timeout) { return NFC_ETIMEOUT; } msleep(pn532_spi_poll_interval); } } return NFC_SUCCESS; } static int pn532_spi_receive_next_chunk(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen) { // According to datasheet, the entire read operation should be done at once // However, it seems impossible to do since the length of the frame is stored in the frame // itself and it's impossible to manually set CS to low between two read operations // It's possible to read the response frame in a series of read operations, provided // each read operation is preceded by SPI_DATAREAD byte from the host. // Unfortunately, the PN532 sends first byte of the second and successive response chunks // at the same time as host sends SPI_DATAREAD byte // Many hardware SPI implementations are half-duplex, so it's became impossible to read this // first response byte // The following hack is used here: we first try to receive data from PN532 without SPI_DATAREAD // and then begin full-featured read operation // The PN532 does not shift the internal register on the receive operation, which allows us to read the whole response // The example transfer log is as follows: // CS ..._/---\___________________________/---\________/------\_____________/-----\_________/---\____________/---... // MOSI (host=>pn532) ... 0x03 0x00 0x00 0x00 0x00 0x00 0x03 0x00 0x00 0x03 0x00 // MISO (pn532<=host) ... 0x01 0x00 0xff 0x02 0xfe 0xd5 0xd5 0x15 0x16 0x16 0x00 // linux send/receive s r r r r r s r r s r // |<-- data -->| |<-data->| |<-data->| |<-data->| |<-data->| // |<-- first chunk -->| |<-- second chunk -->| |<-- third chunk -->| // The response frame is 0x00 0xff 0x02 0xfe 0xd5 0x15 0x16 0x00 int res = spi_receive(DRIVER_DATA(pnd)->port, pbtData, 1, true); if (res != NFC_SUCCESS) { return res; } res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, pbtData + 1, szDataLen - 1, true); return res; } static int pn532_spi_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; pnd->last_error = pn532_spi_wait_for_data(pnd, timeout); if (NFC_EOPABORTED == pnd->last_error) { return pn532_spi_ack(pnd); } if (pnd->last_error != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to wait for SPI data. (RX)"); goto error; } pnd->last_error = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, abtRxBuf , 4, true); if (pnd->last_error < 0) { goto error; } const uint8_t pn53x_long_preamble[3] = { 0x00, 0x00, 0xff }; if (0 == (memcmp(abtRxBuf, pn53x_long_preamble, 3))) { // long preamble // omit first byte for (size_t i = 0; i < 3; ++i) { abtRxBuf[i] = abtRxBuf[i + 1]; } // need one more byte pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf + 3, 1); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive one more byte for long preamble frame. (RX)"); goto error; } } const uint8_t pn53x_preamble[2] = { 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 2))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", " preamble+start code mismatch"); pnd->last_error = NFC_EIO; goto error; } if ((0x01 == abtRxBuf[2]) && (0xff == abtRxBuf[3])) { // Error frame pn532_spi_receive_next_chunk(pnd, abtRxBuf, 3); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; goto error; } else if ((0xff == abtRxBuf[2]) && (0xff == abtRxBuf[3])) { // Extended frame pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 3); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } // (abtRxBuf[0] << 8) + abtRxBuf[1] (LEN) include TFI + (CC+1) len = (abtRxBuf[0] << 8) + abtRxBuf[1] - 2; if (((abtRxBuf[0] + abtRxBuf[1] + abtRxBuf[2]) % 256) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } } else { // Normal frame if (256 != (abtRxBuf[2] + abtRxBuf[3])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[2] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %zu, len: %zu)", szDataLen, len); pnd->last_error = NFC_EIO; goto error; } // TFI + PD0 (CC+1) pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 2); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; goto error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; goto error; } if (len) { pnd->last_error = pn532_spi_receive_next_chunk(pnd, pbtData, len); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } } pnd->last_error = pn532_spi_receive_next_chunk(pnd, abtRxBuf, 2); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); goto error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; goto error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; goto error; } // The PN53x command is done and we successfully received the reply return len; error: return pnd->last_error; } static int pn532_spi_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; switch (CHIP_DATA(pnd)->power_mode) { case LOWVBAT: { /** PN532C106 wakeup. */ if ((res = pn532_spi_wakeup(pnd)) < 0) { return res; } // According to PN532 application note, C106 appendix: to go out Low Vbat mode and enter in normal mode we need to send a SAMConfiguration command if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, 1000)) < 0) { return res; } } break; case POWERDOWN: { if ((res = pn532_spi_wakeup(pnd)) < 0) { return res; } } break; case NORMAL: // Nothing to do :) break; }; uint8_t abtFrame[PN532_BUFFER_LEN + 1] = { pn532_spi_cmd_datawrite, 0x00, 0x00, 0xff }; // SPI data transfer starts with DATAWRITE (0x01) byte, Every packet must start with "00 00 ff" size_t szFrame = 0; if ((res = pn53x_build_frame(abtFrame + 1, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } res = spi_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame, true); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } res = pn532_spi_wait_for_data(pnd, timeout); if (res != NFC_SUCCESS) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to wait for SPI data. (RX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; res = spi_send_receive(DRIVER_DATA(pnd)->port, &pn532_spi_cmd_dataread, 1, abtRxBuf, sizeof(abtRxBuf), true); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else { return pnd->last_error; } return NFC_SUCCESS; } int pn532_spi_ack(nfc_device *pnd) { const size_t ack_frame_len = (sizeof(pn53x_ack_frame) / sizeof(pn53x_ack_frame[0])); uint8_t ack_tx_buf [1 + ack_frame_len]; ack_tx_buf[0] = pn532_spi_cmd_datawrite; memcpy(ack_tx_buf + 1, pn53x_ack_frame, ack_frame_len); int res = spi_send(DRIVER_DATA(pnd)->port, ack_tx_buf, ack_frame_len + 1, true); return res; } static int pn532_spi_abort_command(nfc_device *pnd) { if (pnd) { DRIVER_DATA(pnd)->abort_flag = true; } return NFC_SUCCESS; } const struct pn53x_io pn532_spi_io = { .send = pn532_spi_send, .receive = pn532_spi_receive, }; const struct nfc_driver pn532_spi_driver = { .name = PN532_SPI_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = pn532_spi_scan, .open = pn532_spi_open, .close = pn532_spi_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = pn532_initiator_init_secure_element, .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = pn532_spi_abort_command, .idle = pn53x_idle, .powerdown = pn53x_PowerDown, };
zzyjames55-nfc0805
libnfc/drivers/pn532_spi.c
C
lgpl
21,349
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file arygon.c * @brief ARYGON readers driver * * This driver can handle ARYGON readers that use UART as bus. * UART connection can be direct (host<->arygon_uc) or could be provided by internal USB to serial interface (e.g. host<->ftdi_chip<->arygon_uc) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "arygon.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" /** @def DEV_ARYGON_PROTOCOL_ARYGON_ASCII * @brief High level language in ASCII format. (Common µC commands and Mifare® commands) */ #define DEV_ARYGON_PROTOCOL_ARYGON_ASCII '0' /** @def DEV_ARYGON_MODE_HL_ASCII * @brief High level language in Binary format With AddressingByte for party line. (Common µC commands and Mifare® commands) */ #define DEV_ARYGON_PROTOCOL_ARYGON_BINARY_WAB '1' /** @def DEV_ARYGON_PROTOCOL_TAMA * @brief Philips protocol (TAMA language) in binary format. */ #define DEV_ARYGON_PROTOCOL_TAMA '2' /** @def DEV_ARYGON_PROTOCOL_TAMA_WAB * @brief Philips protocol (TAMA language) in binary With AddressingByte for party line. */ #define DEV_ARYGON_PROTOCOL_TAMA_WAB '3' #define ARYGON_DEFAULT_SPEED 9600 #define ARYGON_DRIVER_NAME "arygon" #define LOG_CATEGORY "libnfc.driver.arygon" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define DRIVER_DATA(pnd) ((struct arygon_data*)(pnd->driver_data)) // Internal data structs const struct pn53x_io arygon_tama_io; struct arygon_data { serial_port port; #ifndef WIN32 int iAbortFds[2]; #else volatile bool abort_flag; #endif }; // ARYGON frames static const uint8_t arygon_error_none[] = "FF000000\x0d\x0a"; static const uint8_t arygon_error_incomplete_command[] = "FF0C0000\x0d\x0a"; static const uint8_t arygon_error_unknown_mode[] = "FF060000\x0d\x0a"; // Prototypes int arygon_reset_tama(nfc_device *pnd); void arygon_firmware(nfc_device *pnd, char *str); static size_t arygon_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find ARYGON device on serial port: %s at %d bauds.", acPort, ARYGON_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp); uart_set_speed(sp, ARYGON_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ARYGON_DRIVER_NAME, acPort, ARYGON_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); return 0; } pnd->driver = &arygon_driver; pnd->driver_data = malloc(sizeof(struct arygon_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return 0; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &arygon_tama_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return 0; } #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif int res = arygon_reset_tama(pnd); uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (res < 0) { continue; } // ARYGON reader is found memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } struct arygon_descriptor { char *port; uint32_t speed; }; static void arygon_close(nfc_device *pnd) { pn53x_idle(pnd); // Release UART port uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->iAbortFds[0]); close(DRIVER_DATA(pnd)->iAbortFds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * arygon_open(const nfc_context *context, const nfc_connstring connstring) { struct arygon_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, ARYGON_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = ARYGON_DEFAULT_SPEED; } serial_port sp; nfc_device *pnd = NULL; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to open: %s at %d bauds.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); if (sp == CLAIMED_SERIAL_PORT) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); if ((sp == CLAIMED_SERIAL_PORT) || (sp == INVALID_SERIAL_PORT)) { free(ndd.port); return NULL; } // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp); uart_set_speed(sp, ndd.speed); // We have a connection pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s:%s", ARYGON_DRIVER_NAME, ndd.port); free(ndd.port); pnd->driver_data = malloc(sizeof(struct arygon_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; // Alloc and init chip's data if (pn53x_data_new(pnd, &arygon_tama_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } // The PN53x chip opened to ARYGON MCU doesn't seems to be in LowVBat mode CHIP_DATA(pnd)->power_mode = NORMAL; // empirical tuning CHIP_DATA(pnd)->timer_correction = 46; pnd->driver = &arygon_driver; #ifndef WIN32 // pipe-based abort mecanism if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif // Check communication using "Reset TAMA" command if (arygon_reset_tama(pnd) < 0) { arygon_close(pnd); return NULL; } char arygon_firmware_version[10]; arygon_firmware(pnd, arygon_firmware_version); char *pcName; pcName = strdup(pnd->name); snprintf(pnd->name, sizeof(pnd->name), "%s %s", pcName, arygon_firmware_version); free(pcName); pn53x_init(pnd); return pnd; } #define ARYGON_TX_BUFFER_LEN (PN53x_NORMAL_FRAME__DATA_MAX_LEN + PN53x_NORMAL_FRAME__OVERHEAD + 1) #define ARYGON_RX_BUFFER_LEN (PN53x_EXTENDED_FRAME__DATA_MAX_LEN + PN53x_EXTENDED_FRAME__OVERHEAD) static int arygon_tama_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout) { int res = 0; // Before sending anything, we need to discard from any junk bytes uart_flush_input(DRIVER_DATA(pnd)->port); uint8_t abtFrame[ARYGON_TX_BUFFER_LEN] = { DEV_ARYGON_PROTOCOL_TAMA, 0x00, 0x00, 0xff }; // Every packet must start with "0x32 0x00 0x00 0xff" size_t szFrame = 0; if (szData > PN53x_NORMAL_FRAME__DATA_MAX_LEN) { // ARYGON Reader with PN532 equipped does not support extended frame (bug in ARYGON firmware?) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "ARYGON device does not support more than %d bytes as payload (requested: %" PRIdPTR ")", PN53x_NORMAL_FRAME__DATA_MAX_LEN, szData); pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } if ((res = pn53x_build_frame(abtFrame + 1, &szFrame, pbtData, szData)) < 0) { pnd->last_error = res; return pnd->last_error; } if ((res = uart_send(DRIVER_DATA(pnd)->port, abtFrame, szFrame + 1, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = res; return pnd->last_error; } uint8_t abtRxBuf[PN53x_ACK_FRAME__LEN]; if ((res = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, sizeof(abtRxBuf), 0, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to read ACK"); pnd->last_error = res; return pnd->last_error; } if (pn53x_check_ack_frame(pnd, abtRxBuf, sizeof(abtRxBuf)) == 0) { // The PN53x is running the sent command } else if (0 == memcmp(arygon_error_unknown_mode, abtRxBuf, sizeof(abtRxBuf))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Bad frame format."); // We have already read 6 bytes and arygon_error_unknown_mode is 10 bytes long // so we have to read 4 remaining bytes to be synchronized at the next receiving pass. pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 4, 0, timeout); return pnd->last_error; } else { return pnd->last_error; } return NFC_SUCCESS; } static int arygon_abort(nfc_device *pnd) { // Send a valid TAMA packet to wakup the PN53x (we will not have an answer, according to Arygon manual) uint8_t dummy[] = { 0x32, 0x00, 0x00, 0xff, 0x09, 0xf7, 0xd4, 0x00, 0x00, 0x6c, 0x69, 0x62, 0x6e, 0x66, 0x63, 0xbe, 0x00 }; uart_send(DRIVER_DATA(pnd)->port, dummy, sizeof(dummy), 0); // Using Arygon device we can't send ACK frame to abort the running command return pn53x_check_communication(pnd); } static int arygon_tama_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout) { uint8_t abtRxBuf[5]; size_t len; void *abort_p = NULL; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->iAbortFds[1]); #else abort_p = (void *) & (DRIVER_DATA(pnd)->abort_flag); #endif pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 5, abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { arygon_abort(pnd); /* last_error got reset by arygon_abort() */ pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } const uint8_t pn53x_preamble[3] = { 0x00, 0x00, 0xff }; if (0 != (memcmp(abtRxBuf, pn53x_preamble, 3))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame preamble+start code mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if ((0x01 == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Error frame uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 3, 0, timeout); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Application level error detected"); pnd->last_error = NFC_EIO; return pnd->last_error; } else if ((0xff == abtRxBuf[3]) && (0xff == abtRxBuf[4])) { // Extended frame // ARYGON devices does not support extended frame sending abort(); } else { // Normal frame if (256 != (abtRxBuf[3] + abtRxBuf[4])) { // TODO: Retry log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Length checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // abtRxBuf[3] (LEN) include TFI + (CC+1) len = abtRxBuf[3] - 2; } if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EIO; return pnd->last_error; } // TFI + PD0 (CC+1) pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } if (abtRxBuf[0] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[1] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (len) { pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, pbtData, len, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } } pnd->last_error = uart_receive(DRIVER_DATA(pnd)->port, abtRxBuf, 2, 0, timeout); if (pnd->last_error != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return pnd->last_error; } uint8_t btDCS = (256 - 0xD5); btDCS -= CHIP_DATA(pnd)->last_command + 1; for (size_t szPos = 0; szPos < len; szPos++) { btDCS -= pbtData[szPos]; } if (btDCS != abtRxBuf[0]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Data checksum mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (0x00 != abtRxBuf[1]) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame postamble mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } // The PN53x command is done and we successfully received the reply return len; } void arygon_firmware(nfc_device *pnd, char *str) { const uint8_t arygon_firmware_version_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'v' }; uint8_t abtRx[16]; size_t szRx = sizeof(abtRx); int res = uart_send(DRIVER_DATA(pnd)->port, arygon_firmware_version_cmd, sizeof(arygon_firmware_version_cmd), 0); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to send ARYGON firmware command."); return; } res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 0); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Unable to retrieve ARYGON firmware version."); return; } if (0 == memcmp(abtRx, arygon_error_none, 6)) { uint8_t *p = abtRx + 6; unsigned int szData; sscanf((const char *)p, "%02x%9s", &szData, p); if (szData > 9) szData = 9; memcpy(str, p, szData); *(str + szData) = '\0'; } } int arygon_reset_tama(nfc_device *pnd) { const uint8_t arygon_reset_tama_cmd[] = { DEV_ARYGON_PROTOCOL_ARYGON_ASCII, 'a', 'r' }; uint8_t abtRx[10]; // Attempted response is 10 bytes long size_t szRx = sizeof(abtRx); int res; uart_send(DRIVER_DATA(pnd)->port, arygon_reset_tama_cmd, sizeof(arygon_reset_tama_cmd), 500); // Two reply are possible from ARYGON device: arygon_error_none (ie. in case the byte is well-sent) // or arygon_error_unknown_mode (ie. in case of the first byte was bad-transmitted) res = uart_receive(DRIVER_DATA(pnd)->port, abtRx, szRx, 0, 1000); if (res != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "No reply to 'reset TAMA' command."); pnd->last_error = res; return pnd->last_error; } if (0 != memcmp(abtRx, arygon_error_none, sizeof(arygon_error_none) - 1)) { pnd->last_error = NFC_EIO; return pnd->last_error; } return NFC_SUCCESS; } static int arygon_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->iAbortFds[0]); if (pipe(DRIVER_DATA(pnd)->iAbortFds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io arygon_tama_io = { .send = arygon_tama_send, .receive = arygon_tama_receive, }; const struct nfc_driver arygon_driver = { .name = ARYGON_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = arygon_scan, .open = arygon_open, .close = arygon_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = arygon_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
zzyjames55-nfc0805
libnfc/drivers/arygon.c
C
lgpl
19,733
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122_pcsc.h * @brief Driver for ACR122 devices (behind PC/SC daemon) */ #ifndef __NFC_DRIVER_ACR122_PCSC_H__ #define __NFC_DRIVER_ACR122_PCSC_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122_pcsc_driver; #endif // ! __NFC_DRIVER_ACR122_PCSC_H__
zzyjames55-nfc0805
libnfc/drivers/acr122_pcsc.h
C
lgpl
1,368
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122_usb.c * @brief Driver for ACR122 using direct USB (without PCSC) */ /* * This implementation was written based on information provided by the * following documents: * * Smart Card CCID * Specification for Integrated Circuit(s) Cards Interface Devices * Revision 1.1 * April 22rd, 2005 * http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.pdf * * ACR122U NFC Reader * Application Programming Interface * Revision 1.2 * http://acs.com.hk/drivers/eng/API_ACR122U.pdf */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H /* Thanks to d18c7db and Okko for example code */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <sys/select.h> #include <errno.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "buses/usbbus.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "drivers/acr122_usb.h" #define ACR122_USB_DRIVER_NAME "acr122_usb" #define LOG_GROUP NFC_LOG_GROUP_DRIVER #define LOG_CATEGORY "libnfc.driver.acr122_usb" #define USB_INFINITE_TIMEOUT 0 #define DRIVER_DATA(pnd) ((struct acr122_usb_data*)(pnd->driver_data)) /* USB activity trace for PN533, ACR122 and Touchatag -------------------------------------------------------------------- PN533 0000ff02fe d402 2a00 0000ff00ff00 ACK 0000ff06fa d50333020707 e500 -------------------------------------------------------------------- Acr122U PICC pseudo-APDU through PCSC Escape mechanism: 6b07000000000a000000 ff00000002 d402 PC_to_RDR_Escape APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=0a RFU=000000 8308000000000a028100 d50332010407 9000 RDR_to_PC_Escape SW: OK Len..... Slot=0 Seq=0a Slot Status=02 ?? Slot Error=81 ?? RFU=00 -------------------------------------------------------------------- Touchatag (Acr122U SAM) pseudo-APDU mechanism: 6f07000000000e000000 ff00000002 d402 PC_to_RDR_XfrBlock APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=0e BWI=00 RFU=0000 8002000000000e000000 6108 RDR_to_PC_DataBlock SW: more data: 8 bytes Slot=0 Seq=0e Slot Status=00 Slot Error=00 RFU=00 6f05000000000f000000 ffc0000008 pseudo-ADPU GetResponse 8008000000000f000000 d50332010407 9000 SW: OK -------------------------------------------------------------------- Apparently Acr122U PICC can also work without Escape (even if there is no card): 6f070000000000000000 ff00000002 d402 PC_to_RDR_XfrBlock APDU Len..... ClInP1P2Lc Slot=0 pseudo-APDU DirectTransmit Seq=00 BWI=00 RFU=0000 80080000000000008100 d50332010407 9000 SW: OK */ #pragma pack(1) struct ccid_header { uint8_t bMessageType; uint32_t dwLength; uint8_t bSlot; uint8_t bSeq; uint8_t bMessageSpecific[3]; }; struct apdu_header { uint8_t bClass; uint8_t bIns; uint8_t bP1; uint8_t bP2; uint8_t bLen; }; struct acr122_usb_tama_frame { struct ccid_header ccid_header; struct apdu_header apdu_header; uint8_t tama_header; uint8_t tama_payload[254]; // According to ACR122U manual: Pseudo APDUs (Section 6.0), Lc is 1-byte long (Data In: 255-bytes). }; struct acr122_usb_apdu_frame { struct ccid_header ccid_header; struct apdu_header apdu_header; uint8_t apdu_payload[255]; // APDU Lc is 1-byte long }; #pragma pack() // Internal data struct struct acr122_usb_data { usb_dev_handle *pudh; uint32_t uiEndPointIn; uint32_t uiEndPointOut; uint32_t uiMaxPacketSize; volatile bool abort_flag; // Keep some buffers to reduce memcpy() usage struct acr122_usb_tama_frame tama_frame; struct acr122_usb_apdu_frame apdu_frame; }; // CCID Bulk-Out messages type #define PC_to_RDR_IccPowerOn 0x62 #define PC_to_RDR_XfrBlock 0x6f #define RDR_to_PC_DataBlock 0x80 // ISO 7816-4 #define SW1_More_Data_Available 0x61 #define SW1_Warning_with_NV_changed 0x63 #define PN53x_Specific_Application_Level_Error_Code 0x7f // This frame template is copied at init time // Its designed for TAMA sending but is also used for simple ADPU frame: acr122_build_frame_from_apdu() will overwrite needed bytes const uint8_t acr122_usb_frame_template[] = { PC_to_RDR_XfrBlock, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // CCID header 0xff, 0x00, 0x00, 0x00, 0x00, // ADPU header 0xd4, // PN532 direction }; // APDUs instructions #define APDU_GetAdditionnalData 0xc0 // Internal io struct const struct pn53x_io acr122_usb_io; // Prototypes static int acr122_usb_init(nfc_device *pnd); static int acr122_usb_ack(nfc_device *pnd); static int acr122_usb_send_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *const data, size_t data_len, const uint8_t le, uint8_t *out, const size_t out_size); static int acr122_usb_bulk_read(struct acr122_usb_data *data, uint8_t abtRx[], const size_t szRx, const int timeout) { int res = usb_bulk_read(data->pudh, data->uiEndPointIn, (char *) abtRx, szRx, timeout); if (res > 0) { LOG_HEX(NFC_LOG_GROUP_COM, "RX", abtRx, res); } else if (res < 0) { if (res != -USB_TIMEDOUT) { res = NFC_EIO; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to read from USB (%s)", _usb_strerror(res)); } else { res = NFC_ETIMEOUT; } } return res; } static int acr122_usb_bulk_write(struct acr122_usb_data *data, uint8_t abtTx[], const size_t szTx, const int timeout) { LOG_HEX(NFC_LOG_GROUP_COM, "TX", abtTx, szTx); int res = usb_bulk_write(data->pudh, data->uiEndPointOut, (char *) abtTx, szTx, timeout); if (res > 0) { // HACK This little hack is a well know problem of USB, see http://www.libusb.org/ticket/6 for more details if ((res % data->uiMaxPacketSize) == 0) { usb_bulk_write(data->pudh, data->uiEndPointOut, "\0", 0, timeout); } } else if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to write to USB (%s)", _usb_strerror(res)); if (res == -USB_TIMEDOUT) { res = NFC_ETIMEOUT; } else { res = NFC_EIO; } } return res; } struct acr122_usb_supported_device { uint16_t vendor_id; uint16_t product_id; const char *name; }; const struct acr122_usb_supported_device acr122_usb_supported_devices[] = { { 0x072F, 0x2200, "ACS ACR122" }, { 0x072F, 0x90CC, "Touchatag" }, }; // Find transfer endpoints for bulk transfers static void acr122_usb_get_end_points(struct usb_device *dev, struct acr122_usb_data *data) { uint32_t uiIndex; uint32_t uiEndPoint; struct usb_interface_descriptor *puid = dev->config->interface->altsetting; // 3 Endpoints maximum: Interrupt In, Bulk In, Bulk Out for (uiIndex = 0; uiIndex < puid->bNumEndpoints; uiIndex++) { // Only accept bulk transfer endpoints (ignore interrupt endpoints) if (puid->endpoint[uiIndex].bmAttributes != USB_ENDPOINT_TYPE_BULK) continue; // Copy the endpoint to a local var, makes it more readable code uiEndPoint = puid->endpoint[uiIndex].bEndpointAddress; // Test if we dealing with a bulk IN endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_IN) { data->uiEndPointIn = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } // Test if we dealing with a bulk OUT endpoint if ((uiEndPoint & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_OUT) { data->uiEndPointOut = uiEndPoint; data->uiMaxPacketSize = puid->endpoint[uiIndex].wMaxPacketSize; } } } static size_t acr122_usb_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { (void)context; usb_prepare(); size_t device_found = 0; uint32_t uiBusIndex = 0; struct usb_bus *bus; for (bus = usb_get_busses(); bus; bus = bus->next) { struct usb_device *dev; for (dev = bus->devices; dev; dev = dev->next, uiBusIndex++) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) { if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { // Make sure there are 2 endpoints available // with libusb-win32 we got some null pointers so be robust before looking at endpoints: if (dev->config == NULL || dev->config->interface == NULL || dev->config->interface->altsetting == NULL) { // Nope, we maybe want the next one, let's try to find another continue; } if (dev->config->interface->altsetting->bNumEndpoints < 2) { // Nope, we maybe want the next one, let's try to find another continue; } usb_dev_handle *udev = usb_open(dev); if (udev == NULL) continue; // Set configuration // acr122_usb_get_usb_device_name (dev, udev, pnddDevices[device_found].acDevice, sizeof (pnddDevices[device_found].acDevice)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "device found: Bus %s Device %s Name %s", bus->dirname, dev->filename, acr122_usb_supported_devices[n].name); usb_close(udev); snprintf(connstrings[device_found], sizeof(nfc_connstring), "%s:%s:%s", ACR122_USB_DRIVER_NAME, bus->dirname, dev->filename); device_found++; // Test if we reach the maximum "wanted" devices if (device_found == connstrings_len) { return device_found; } } } } } return device_found; } struct acr122_usb_descriptor { char *dirname; char *filename; }; static bool acr122_usb_get_usb_device_name(struct usb_device *dev, usb_dev_handle *udev, char *buffer, size_t len) { *buffer = '\0'; if (dev->descriptor.iManufacturer || dev->descriptor.iProduct) { if (udev) { usb_get_string_simple(udev, dev->descriptor.iManufacturer, buffer, len); if (strlen(buffer) > 0) strcpy(buffer + strlen(buffer), " / "); usb_get_string_simple(udev, dev->descriptor.iProduct, buffer + strlen(buffer), len - strlen(buffer)); } } if (!*buffer) { for (size_t n = 0; n < sizeof(acr122_usb_supported_devices) / sizeof(struct acr122_usb_supported_device); n++) { if ((acr122_usb_supported_devices[n].vendor_id == dev->descriptor.idVendor) && (acr122_usb_supported_devices[n].product_id == dev->descriptor.idProduct)) { strncpy(buffer, acr122_usb_supported_devices[n].name, len); buffer[len - 1] = '\0'; return true; } } } return false; } static nfc_device * acr122_usb_open(const nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; struct acr122_usb_descriptor desc = { NULL, NULL }; int connstring_decode_level = connstring_decode(connstring, ACR122_USB_DRIVER_NAME, "usb", &desc.dirname, &desc.filename); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d element(s) have been decoded from \"%s\"", connstring_decode_level, connstring); if (connstring_decode_level < 1) { goto free_mem; } struct acr122_usb_data data = { .pudh = NULL, .uiEndPointIn = 0, .uiEndPointOut = 0, }; struct usb_bus *bus; struct usb_device *dev; usb_prepare(); for (bus = usb_get_busses(); bus; bus = bus->next) { if (connstring_decode_level > 1) { // A specific bus have been specified if (0 != strcmp(bus->dirname, desc.dirname)) continue; } for (dev = bus->devices; dev; dev = dev->next) { if (connstring_decode_level > 2) { // A specific dev have been specified if (0 != strcmp(dev->filename, desc.filename)) continue; } // Open the USB device if ((data.pudh = usb_open(dev)) == NULL) continue; // Reset device usb_reset(data.pudh); // Retrieve end points acr122_usb_get_end_points(dev, &data); // Claim interface int res = usb_claim_interface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to claim USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } res = usb_set_altinterface(data.pudh, 0); if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set alternate setting on USB interface (%s)", _usb_strerror(res)); usb_close(data.pudh); // we failed to use the specified device goto free_mem; } // Allocate memory for the device info and specification, fill it and return the info pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); goto error; } acr122_usb_get_usb_device_name(dev, data.pudh, pnd->name, sizeof(pnd->name)); pnd->driver_data = malloc(sizeof(struct acr122_usb_data)); if (!pnd->driver_data) { perror("malloc"); goto error; } *DRIVER_DATA(pnd) = data; // Alloc and init chip's data if (pn53x_data_new(pnd, &acr122_usb_io) == NULL) { perror("malloc"); goto error; } memcpy(&(DRIVER_DATA(pnd)->tama_frame), acr122_usb_frame_template, sizeof(acr122_usb_frame_template)); memcpy(&(DRIVER_DATA(pnd)->apdu_frame), acr122_usb_frame_template, sizeof(acr122_usb_frame_template)); CHIP_DATA(pnd)->timer_correction = 46; // empirical tuning pnd->driver = &acr122_usb_driver; if (acr122_usb_init(pnd) < 0) { usb_close(data.pudh); goto error; } DRIVER_DATA(pnd)->abort_flag = false; goto free_mem; } } // We ran out of devices before the index required goto free_mem; error: // Free allocated structure on error. nfc_device_free(pnd); pnd = NULL; free_mem: free(desc.dirname); free(desc.filename); return pnd; } static void acr122_usb_close(nfc_device *pnd) { acr122_usb_ack(pnd); pn53x_idle(pnd); int res; if ((res = usb_release_interface(DRIVER_DATA(pnd)->pudh, 0)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to release USB interface (%s)", _usb_strerror(res)); } if ((res = usb_close(DRIVER_DATA(pnd)->pudh)) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to close USB connection (%s)", _usb_strerror(res)); } pn53x_data_free(pnd); nfc_device_free(pnd); } #if !defined(htole32) uint32_t htole32(uint32_t u32); uint32_t htole32(uint32_t u32) { union { uint8_t arr[4]; uint32_t u32; } u; for (int i = 0; i < 4; i++) { u.arr[i] = (u32 & 0xff); u32 >>= 8; } return u.u32; } #endif /* !defined(htole32) */ static int acr122_build_frame_from_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *data, const size_t data_len, const uint8_t le) { if (data_len > sizeof(DRIVER_DATA(pnd)->apdu_frame.apdu_payload)) return NFC_EINVARG; if ((data == NULL) && (data_len != 0)) return NFC_EINVARG; DRIVER_DATA(pnd)->apdu_frame.ccid_header.dwLength = htole32(data_len + sizeof(struct apdu_header)); DRIVER_DATA(pnd)->apdu_frame.apdu_header.bIns = ins; DRIVER_DATA(pnd)->apdu_frame.apdu_header.bP1 = p1; DRIVER_DATA(pnd)->apdu_frame.apdu_header.bP2 = p2; if (data) { // bLen is Lc when data != NULL DRIVER_DATA(pnd)->apdu_frame.apdu_header.bLen = data_len; memcpy(DRIVER_DATA(pnd)->apdu_frame.apdu_payload, data, data_len); } else { // bLen is Le when no data. DRIVER_DATA(pnd)->apdu_frame.apdu_header.bLen = le; } return (sizeof(struct ccid_header) + sizeof(struct apdu_header) + data_len); } static int acr122_build_frame_from_tama(nfc_device *pnd, const uint8_t *tama, const size_t tama_len) { if (tama_len > sizeof(DRIVER_DATA(pnd)->tama_frame.tama_payload)) return NFC_EINVARG; DRIVER_DATA(pnd)->tama_frame.ccid_header.dwLength = htole32(tama_len + sizeof(struct apdu_header) + 1); DRIVER_DATA(pnd)->tama_frame.apdu_header.bLen = tama_len + 1; memcpy(DRIVER_DATA(pnd)->tama_frame.tama_payload, tama, tama_len); return (sizeof(struct ccid_header) + sizeof(struct apdu_header) + 1 + tama_len); } static int acr122_usb_send(nfc_device *pnd, const uint8_t *pbtData, const size_t szData, const int timeout) { int res; if ((res = acr122_build_frame_from_tama(pnd, pbtData, szData)) < 0) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->tama_frame), res, timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } return NFC_SUCCESS; } #define USB_TIMEOUT_PER_PASS 200 static int acr122_usb_receive(nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, const int timeout) { off_t offset = 0; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; int res; /* * If no timeout is specified but the command is blocking, force a 200ms (USB_TIMEOUT_PER_PASS) * timeout to allow breaking the loop if the user wants to stop it. */ int usb_timeout; int remaining_time = timeout; read: if (timeout == USB_INFINITE_TIMEOUT) { usb_timeout = USB_TIMEOUT_PER_PASS; } else { // A user-provided timeout is set, we have to cut it in multiple chunk to be able to keep an nfc_abort_command() mecanism remaining_time -= USB_TIMEOUT_PER_PASS; if (remaining_time <= 0) { pnd->last_error = NFC_ETIMEOUT; return pnd->last_error; } else { usb_timeout = MIN(remaining_time, USB_TIMEOUT_PER_PASS); } } res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), usb_timeout); uint8_t attempted_response = RDR_to_PC_DataBlock; size_t len; if (res == NFC_ETIMEOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; acr122_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; } } if (res < 12) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Invalid RDR_to_PC_DataBlock frame"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[offset] != attempted_response) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame header mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset++; len = abtRxBuf[offset++]; if (!((len > 1) && (abtRxBuf[10] == 0xd5))) { // In case we didn't get an immediate answer: if (len != 2) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Wrong reply"); pnd->last_error = NFC_EIO; return pnd->last_error; } if (abtRxBuf[10] != SW1_More_Data_Available) { if ((abtRxBuf[10] == SW1_Warning_with_NV_changed) && (abtRxBuf[11] == PN53x_Specific_Application_Level_Error_Code)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 has detected an error at the application level"); } else if ((abtRxBuf[10] == SW1_Warning_with_NV_changed) && (abtRxBuf[11] == 0x00)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 didn't reply"); } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unexpected Status Word (SW1: %02x SW2: %02x)", abtRxBuf[10], abtRxBuf[11]); } pnd->last_error = NFC_EIO; return pnd->last_error; } acr122_usb_send_apdu(pnd, APDU_GetAdditionnalData, 0x00, 0x00, NULL, 0, abtRxBuf[11], abtRxBuf, sizeof(abtRxBuf)); } offset = 0; if (res == NFC_ETIMEOUT) { if (DRIVER_DATA(pnd)->abort_flag) { DRIVER_DATA(pnd)->abort_flag = false; acr122_usb_ack(pnd); pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } else { goto read; // FIXME May cause some trouble on Touchatag, right ? } } if (res < 0) { // try to interrupt current device state acr122_usb_ack(pnd); pnd->last_error = res; return pnd->last_error; } if (abtRxBuf[offset] != attempted_response) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Frame header mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset++; // XXX In CCID specification, len is a 32-bits (dword), do we need to decode more than 1 byte ? (0-255 bytes for PN532 reply) len = abtRxBuf[offset++]; if ((abtRxBuf[offset] != 0x00) && (abtRxBuf[offset + 1] != 0x00) && (abtRxBuf[offset + 2] != 0x00)) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Not implemented: only 1-byte length is supported, please report this bug with a full trace."); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 3; if (len < 4) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Too small reply"); pnd->last_error = NFC_EIO; return pnd->last_error; } len -= 4; // We skip 2 bytes for PN532 direction byte (D5) and command byte (CMD+1), then 2 bytes for APDU status (90 00). if (len > szDataLen) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to receive data: buffer too small. (szDataLen: %" PRIuPTR ", len: %" PRIuPTR ")", szDataLen, len); pnd->last_error = NFC_EOVFLOW; return pnd->last_error; } // Skip CCID remaining bytes offset += 2; // bSlot and bSeq are not used offset += 2; // XXX bStatus and bError should maybe checked ? offset += 1; // bRFU should be 0x00 // TFI + PD0 (CC+1) if (abtRxBuf[offset] != 0xD5) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "TFI Mismatch"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; if (abtRxBuf[offset] != CHIP_DATA(pnd)->last_command + 1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Command Code verification failed"); pnd->last_error = NFC_EIO; return pnd->last_error; } offset += 1; memcpy(pbtData, abtRxBuf + offset, len); return len; } int acr122_usb_ack(nfc_device *pnd) { (void) pnd; int res = 0; uint8_t acr122_ack_frame[] = { GetFirmwareVersion }; // We can't send a PN532's ACK frame, so we use a normal command to cancel current command log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 Abort"); if ((res = acr122_build_frame_from_tama(pnd, acr122_ack_frame, sizeof(acr122_ack_frame))) < 0) return res; if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->tama_frame), res, 1000)) < 0) return res; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000); return res; } static int acr122_usb_send_apdu(nfc_device *pnd, const uint8_t ins, const uint8_t p1, const uint8_t p2, const uint8_t *const data, size_t data_len, const uint8_t le, uint8_t *out, const size_t out_size) { int res; size_t frame_len = acr122_build_frame_from_apdu(pnd, ins, p1, p2, data, data_len, le); if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), (unsigned char *) & (DRIVER_DATA(pnd)->apdu_frame), frame_len, 1000)) < 0) return res; if ((res = acr122_usb_bulk_read(DRIVER_DATA(pnd), out, out_size, 1000)) < 0) return res; return res; } int acr122_usb_init(nfc_device *pnd) { int res = 0; int i; uint8_t abtRxBuf[255 + sizeof(struct ccid_header)]; /* // See ACR122 manual: "Bi-Color LED and Buzzer Control" section uint8_t acr122u_get_led_state_frame[] = { 0x6b, // CCID 0x09, // lenght of frame 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding // frame: 0xff, // Class 0x00, // INS 0x40, // P1: Get LED state command 0x00, // P2: LED state control 0x04, // Lc 0x00, 0x00, 0x00, 0x00, // Blinking duration control }; log_put (LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 Get LED state"); if ((res = acr122_usb_bulk_write (DRIVER_DATA (pnd), (uint8_t *) acr122u_get_led_state_frame, sizeof (acr122u_get_led_state_frame), 1000)) < 0) return res; if ((res = acr122_usb_bulk_read (DRIVER_DATA (pnd), abtRxBuf, sizeof (abtRxBuf), 1000)) < 0) return res; */ if ((res = pn53x_set_property_int(pnd, NP_TIMEOUT_COMMAND, 1000)) < 0) return res; // Power On ICC uint8_t ccid_frame[] = { PC_to_RDR_IccPowerOn, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00 }; if ((res = acr122_usb_bulk_write(DRIVER_DATA(pnd), ccid_frame, sizeof(struct ccid_header), 1000)) < 0) return res; if ((res = acr122_usb_bulk_read(DRIVER_DATA(pnd), abtRxBuf, sizeof(abtRxBuf), 1000)) < 0) return res; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "ACR122 PICC Operating Parameters"); if ((res = acr122_usb_send_apdu(pnd, 0x00, 0x51, 0x00, NULL, 0, 0, abtRxBuf, sizeof(abtRxBuf))) < 0) return res; res = 0; for (i = 0; i < 3; i++) { if (res < 0) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "PN532 init failed, trying again..."); if ((res = pn53x_init(pnd)) >= 0) break; } if (res < 0) return res; return NFC_SUCCESS; } static int acr122_usb_abort_command(nfc_device *pnd) { DRIVER_DATA(pnd)->abort_flag = true; return NFC_SUCCESS; } const struct pn53x_io acr122_usb_io = { .send = acr122_usb_send, .receive = acr122_usb_receive, }; const struct nfc_driver acr122_usb_driver = { .name = ACR122_USB_DRIVER_NAME, .scan_type = NOT_INTRUSIVE, .scan = acr122_usb_scan, .open = acr122_usb_open, .close = acr122_usb_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = acr122_usb_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
zzyjames55-nfc0805
libnfc/drivers/acr122_usb.c
C
lgpl
29,046
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122_usb.h * @brief Driver for ACR122 devices using direct USB connection (without PCSC) */ #ifndef __NFC_DRIVER_ACR122_USB_H__ #define __NFC_DRIVER_ACR122_USB_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver acr122_usb_driver; #endif // ! __NFC_DRIVER_ACR122_USB_H__
zzyjames55-nfc0805
libnfc/drivers/acr122_usb.h
C
lgpl
1,384
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn53x_usb.h * @brief Drive for PN53x USB devices */ #ifndef __NFC_DRIVER_PN53X_USB_H__ #define __NFC_DRIVER_PN53X_USB_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver pn53x_usb_driver; #endif // ! __NFC_DRIVER_PN53X_USB_H__
zzyjames55-nfc0805
libnfc/drivers/pn53x_usb.h
C
lgpl
1,338
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2011 Anugrah Redja Kusuma * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file acr122s.c * @brief Driver for ACS ACR122S devices */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "acr122s.h" #include <stdio.h> #include <inttypes.h> #include <string.h> #include <string.h> #include <unistd.h> #include <nfc/nfc.h> #include "drivers.h" #include "nfc-internal.h" #include "chips/pn53x.h" #include "chips/pn53x-internal.h" #include "uart.h" #define ACR122S_DEFAULT_SPEED 9600 #define ACR122S_DRIVER_NAME "ACR122S" #define LOG_CATEGORY "libnfc.driver.acr122s" #define LOG_GROUP NFC_LOG_GROUP_DRIVER // Internal data structs struct acr122s_data { serial_port port; uint8_t seq; #ifndef WIN32 int abort_fds[2]; #else volatile bool abort_flag; #endif }; const struct pn53x_io acr122s_io; #define STX 2 #define ETX 3 #define APDU_SIZE(p) ((uint32_t) (p[2] | p[3] << 8 | p[4] << 16 | p[5] << 24)) #define FRAME_OVERHEAD 13 #define FRAME_SIZE(p) (APDU_SIZE(p) + FRAME_OVERHEAD) #define MAX_FRAME_SIZE (FRAME_OVERHEAD + 5 + 255) enum { ICC_POWER_ON_REQ_MSG = 0x62, ICC_POWER_OFF_REQ_MSG = 0x63, XFR_BLOCK_REQ_MSG = 0x6F, ICC_POWER_ON_RES_MSG = 0x80, ICC_POWER_OFF_RES_MSG = 0x81, XFR_BLOCK_RES_MSG = 0x80, }; enum { POWER_AUTO = 0, POWER_5_0_V = 1, POWER_3_0_V = 2, POWER_1_8_V = 3, }; #pragma pack(push, 1) struct icc_power_on_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t power_select; uint8_t rfu[2]; }; struct icc_power_on_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t chain_parameter; }; struct icc_power_off_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t rfu[3]; }; struct icc_power_off_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t clock_status; }; struct xfr_block_req { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t bwi; uint8_t rfu[2]; }; struct xfr_block_res { uint8_t message_type; uint32_t length; uint8_t slot; uint8_t seq; uint8_t status; uint8_t error; uint8_t chain_parameter; }; struct apdu_header { uint8_t class; uint8_t ins; uint8_t p1; uint8_t p2; uint8_t length; }; #pragma pack(pop) #define DRIVER_DATA(pnd) ((struct acr122s_data *) (pnd->driver_data)) /** * Fix a command frame with a valid prefix, checksum, and suffix. * * @param frame is command frame to fix * @note command frame length (uint32_t at offset 2) should be valid */ static void acr122s_fix_frame(uint8_t *frame) { size_t frame_size = FRAME_SIZE(frame); frame[0] = STX; frame[frame_size - 1] = ETX; uint8_t *csum = frame + frame_size - 2; *csum = 0; for (uint8_t *p = frame + 1; p < csum; p++) *csum ^= *p; } /** * Send a command frame to ACR122S and check its ACK status. * * @param: pnd is target nfc device * @param: cmd is command frame to send * @param: timeout * @return 0 if success */ static int acr122s_send_frame(nfc_device *pnd, uint8_t *frame, int timeout) { size_t frame_size = FRAME_SIZE(frame); uint8_t ack[4]; uint8_t positive_ack[4] = { STX, 0, 0, ETX }; serial_port port = DRIVER_DATA(pnd)->port; int ret; void *abort_p; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->abort_fds[1]); #else abort_p = &(DRIVER_DATA(pnd)->abort_flag); #endif if ((ret = uart_send(port, frame, frame_size, timeout)) < 0) return ret; if ((ret = uart_receive(port, ack, 4, abort_p, timeout)) < 0) return ret; if (memcmp(ack, positive_ack, 4) != 0) { pnd->last_error = NFC_EIO; return pnd->last_error; } struct xfr_block_req *req = (struct xfr_block_req *) &frame[1]; DRIVER_DATA(pnd)->seq = req->seq + 1; return 0; } /** * Receive response frame after a successfull acr122s_send_command(). * * @param: pnd is target nfc device * @param: frame is buffer where received response frame will be stored * @param: frame_size is frame size * @param: abort_p * @param: timeout * @note returned frame size can be fetched using FRAME_SIZE macro * * @return 0 if success */ static int acr122s_recv_frame(nfc_device *pnd, uint8_t *frame, size_t frame_size, void *abort_p, int timeout) { if (frame_size < 13) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } int ret; serial_port port = DRIVER_DATA(pnd)->port; if ((ret = uart_receive(port, frame, 11, abort_p, timeout)) != 0) return ret; // Is buffer sufficient to store response? if (frame_size < FRAME_SIZE(frame)) { pnd->last_error = NFC_EIO; return pnd->last_error; } size_t remaining = FRAME_SIZE(frame) - 11; if ((ret = uart_receive(port, frame + 11, remaining, abort_p, timeout)) != 0) return ret; struct xfr_block_res *res = (struct xfr_block_res *) &frame[1]; if ((uint8_t)(res->seq + 1) != DRIVER_DATA(pnd)->seq) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Invalid response sequence number."); pnd->last_error = NFC_EIO; return pnd->last_error; } return 0; } #define APDU_OVERHEAD (FRAME_OVERHEAD + 5) /** * Convert host uint32 to litle endian uint32 */ static uint32_t le32(uint32_t val) { uint32_t res; uint8_t *p = (uint8_t *) &res; p[0] = val; p[1] = val >> 8; p[2] = val >> 16; p[3] = val >> 24; return res; } /** * Build an ACR122S command frame from a PN532 command. * * @param pnd is device for which the command frame will be generated * @param frame is where the resulting command frame will be generated * @param frame_size is the passed command frame size * @param p1 * @param p2 * @param data is PN532 APDU data without the direction prefix (0xD4) * @param data_size is APDU data size * @param should_prefix 1 if prefix 0xD4 should be inserted before APDU data, 0 if not * * @return true if frame built successfully */ static bool acr122s_build_frame(nfc_device *pnd, uint8_t *frame, size_t frame_size, uint8_t p1, uint8_t p2, const uint8_t *data, size_t data_size, int should_prefix) { if (frame_size < data_size + APDU_OVERHEAD + should_prefix) return false; if (data_size + should_prefix > 255) return false; if (data == NULL) return false; struct xfr_block_req *req = (struct xfr_block_req *) &frame[1]; req->message_type = XFR_BLOCK_REQ_MSG; req->length = le32(5 + data_size + should_prefix); req->slot = 0; req->seq = DRIVER_DATA(pnd)->seq; req->bwi = 0; req->rfu[0] = 0; req->rfu[1] = 0; struct apdu_header *header = (struct apdu_header *) &frame[11]; header->class = 0xff; header->ins = 0; header->p1 = p1; header->p2 = p2; header->length = data_size + should_prefix; uint8_t *buf = (uint8_t *) &frame[16]; if (should_prefix) *buf++ = 0xD4; memcpy(buf, data, data_size); acr122s_fix_frame(frame); return true; } static int acr122s_activate_sam(nfc_device *pnd) { uint8_t cmd[13]; memset(cmd, 0, sizeof(cmd)); cmd[1] = ICC_POWER_ON_REQ_MSG; acr122s_fix_frame(cmd); uint8_t resp[MAX_FRAME_SIZE]; int ret; if ((ret = acr122s_send_frame(pnd, cmd, 0)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, resp, MAX_FRAME_SIZE, 0, 0)) != 0) return ret; CHIP_DATA(pnd)->power_mode = NORMAL; return 0; } static int acr122s_deactivate_sam(nfc_device *pnd) { uint8_t cmd[13]; memset(cmd, 0, sizeof(cmd)); cmd[1] = ICC_POWER_OFF_REQ_MSG; acr122s_fix_frame(cmd); uint8_t resp[MAX_FRAME_SIZE]; int ret; if ((ret = acr122s_send_frame(pnd, cmd, 0)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, resp, MAX_FRAME_SIZE, 0, 0)) != 0) return ret; CHIP_DATA(pnd)->power_mode = LOWVBAT; return 0; } static int acr122s_get_firmware_version(nfc_device *pnd, char *version, size_t length) { int ret; uint8_t cmd[MAX_FRAME_SIZE]; if (! acr122s_build_frame(pnd, cmd, sizeof(cmd), 0x48, 0, NULL, 0, 0)) { return NFC_EINVARG; } if ((ret = acr122s_send_frame(pnd, cmd, 1000)) != 0) return ret; if ((ret = acr122s_recv_frame(pnd, cmd, sizeof(cmd), 0, 0)) != 0) return ret; size_t len = APDU_SIZE(cmd); if (len + 1 > length) len = length - 1; memcpy(version, cmd + 11, len); version[len] = 0; return 0; } struct acr122s_descriptor { char *port; uint32_t speed; }; static size_t acr122s_scan(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; serial_port sp; char **acPorts = uart_list_ports(); const char *acPort; int iDevice = 0; while ((acPort = acPorts[iDevice++])) { sp = uart_open(acPort); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Trying to find ACR122S device on serial port: %s at %d bauds.", acPort, ACR122S_DEFAULT_SPEED); if ((sp != INVALID_SERIAL_PORT) && (sp != CLAIMED_SERIAL_PORT)) { // We need to flush input to be sure first reply does not comes from older byte transceive uart_flush_input(sp); uart_set_speed(sp, ACR122S_DEFAULT_SPEED); nfc_connstring connstring; snprintf(connstring, sizeof(nfc_connstring), "%s:%s:%"PRIu32, ACR122S_DRIVER_NAME, acPort, ACR122S_DEFAULT_SPEED); nfc_device *pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); uart_close(sp); return -1; } pnd->driver = &acr122s_driver; pnd->driver_data = malloc(sizeof(struct acr122s_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return -1; } DRIVER_DATA(pnd)->port = sp; DRIVER_DATA(pnd)->seq = 0; #ifndef WIN32 if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return 0; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif if (pn53x_data_new(pnd, &acr122s_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return 0; } CHIP_DATA(pnd)->type = PN532; CHIP_DATA(pnd)->power_mode = NORMAL; char version[32]; int ret = acr122s_get_firmware_version(pnd, version, sizeof(version)); if (ret == 0 && strncmp("ACR122S", version, 7) != 0) { ret = -1; } uart_close(DRIVER_DATA(pnd)->port); pn53x_data_free(pnd); nfc_device_free(pnd); if (ret != 0) continue; // ACR122S reader is found memcpy(connstrings[device_found], connstring, sizeof(nfc_connstring)); device_found++; // Test if we reach the maximum "wanted" devices if (device_found >= connstrings_len) break; } } iDevice = 0; while ((acPort = acPorts[iDevice++])) { free((void *)acPort); } free(acPorts); return device_found; } static void acr122s_close(nfc_device *pnd) { acr122s_deactivate_sam(pnd); pn53x_idle(pnd); uart_close(DRIVER_DATA(pnd)->port); #ifndef WIN32 // Release file descriptors used for abort mecanism close(DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[1]); #endif pn53x_data_free(pnd); nfc_device_free(pnd); } static nfc_device * acr122s_open(const nfc_context *context, const nfc_connstring connstring) { serial_port sp; nfc_device *pnd; struct acr122s_descriptor ndd; char *speed_s; int connstring_decode_level = connstring_decode(connstring, ACR122S_DRIVER_NAME, NULL, &ndd.port, &speed_s); if (connstring_decode_level == 3) { ndd.speed = 0; if (sscanf(speed_s, "%10"PRIu32, &ndd.speed) != 1) { // speed_s is not a number free(ndd.port); free(speed_s); return NULL; } free(speed_s); } if (connstring_decode_level < 2) { return NULL; } if (connstring_decode_level < 3) { ndd.speed = ACR122S_DEFAULT_SPEED; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Attempt to connect to: %s at %d bauds.", ndd.port, ndd.speed); sp = uart_open(ndd.port); if (sp == INVALID_SERIAL_PORT) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid serial port: %s", ndd.port); free(ndd.port); return NULL; } if (sp == CLAIMED_SERIAL_PORT) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Serial port already claimed: %s", ndd.port); free(ndd.port); return NULL; } uart_flush_input(sp); uart_set_speed(sp, ndd.speed); pnd = nfc_device_new(context, connstring); if (!pnd) { perror("malloc"); free(ndd.port); uart_close(sp); return NULL; } pnd->driver = &acr122s_driver; strcpy(pnd->name, ACR122S_DRIVER_NAME); free(ndd.port); pnd->driver_data = malloc(sizeof(struct acr122s_data)); if (!pnd->driver_data) { perror("malloc"); uart_close(sp); nfc_device_free(pnd); return NULL; } DRIVER_DATA(pnd)->port = sp; DRIVER_DATA(pnd)->seq = 0; #ifndef WIN32 if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } #else DRIVER_DATA(pnd)->abort_flag = false; #endif if (pn53x_data_new(pnd, &acr122s_io) == NULL) { perror("malloc"); uart_close(DRIVER_DATA(pnd)->port); nfc_device_free(pnd); return NULL; } CHIP_DATA(pnd)->type = PN532; #if 1 // Retrieve firmware version char version[DEVICE_NAME_LENGTH]; if (acr122s_get_firmware_version(pnd, version, sizeof(version)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Cannot get reader firmware."); acr122s_close(pnd); return NULL; } if (strncmp(version, "ACR122S", 7) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid firmware version: %s", version); acr122s_close(pnd); return NULL; } snprintf(pnd->name, sizeof(pnd->name), "%s", version); // Activate SAM before operating if (acr122s_activate_sam(pnd) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Cannot activate SAM."); acr122s_close(pnd); return NULL; } #endif if (pn53x_init(pnd) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Failed initializing PN532 chip."); acr122s_close(pnd); return NULL; } return pnd; } static int acr122s_send(nfc_device *pnd, const uint8_t *buf, const size_t buf_len, int timeout) { uart_flush_input(DRIVER_DATA(pnd)->port); uint8_t cmd[MAX_FRAME_SIZE]; if (! acr122s_build_frame(pnd, cmd, sizeof(cmd), 0, 0, buf, buf_len, 1)) { return NFC_EINVARG; } int ret; if ((ret = acr122s_send_frame(pnd, cmd, timeout)) != 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to transmit data. (TX)"); pnd->last_error = ret; return pnd->last_error; } return NFC_SUCCESS; } static int acr122s_receive(nfc_device *pnd, uint8_t *buf, size_t buf_len, int timeout) { void *abort_p; #ifndef WIN32 abort_p = &(DRIVER_DATA(pnd)->abort_fds[1]); #else abort_p = &(DRIVER_DATA(pnd)->abort_flag); #endif uint8_t tmp[MAX_FRAME_SIZE]; pnd->last_error = acr122s_recv_frame(pnd, tmp, sizeof(tmp), abort_p, timeout); if (abort_p && (NFC_EOPABORTED == pnd->last_error)) { pnd->last_error = NFC_EOPABORTED; return pnd->last_error; } if (pnd->last_error < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to receive data. (RX)"); return -1; } size_t data_len = FRAME_SIZE(tmp) - 17; if (data_len > buf_len) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Receive buffer too small. (buf_len: %" PRIuPTR ", data_len: %" PRIuPTR ")", buf_len, data_len); pnd->last_error = NFC_EIO; return pnd->last_error; } memcpy(buf, tmp + 13, data_len); return data_len; } static int acr122s_abort_command(nfc_device *pnd) { if (pnd) { #ifndef WIN32 close(DRIVER_DATA(pnd)->abort_fds[0]); close(DRIVER_DATA(pnd)->abort_fds[1]); if (pipe(DRIVER_DATA(pnd)->abort_fds) < 0) { return NFC_ESOFT; } #else DRIVER_DATA(pnd)->abort_flag = true; #endif } return NFC_SUCCESS; } const struct pn53x_io acr122s_io = { .send = acr122s_send, .receive = acr122s_receive, }; const struct nfc_driver acr122s_driver = { .name = ACR122S_DRIVER_NAME, .scan_type = INTRUSIVE, .scan = acr122s_scan, .open = acr122s_open, .close = acr122s_close, .strerror = pn53x_strerror, .initiator_init = pn53x_initiator_init, .initiator_init_secure_element = NULL, // No secure-element support .initiator_select_passive_target = pn53x_initiator_select_passive_target, .initiator_poll_target = pn53x_initiator_poll_target, .initiator_select_dep_target = pn53x_initiator_select_dep_target, .initiator_deselect_target = pn53x_initiator_deselect_target, .initiator_transceive_bytes = pn53x_initiator_transceive_bytes, .initiator_transceive_bits = pn53x_initiator_transceive_bits, .initiator_transceive_bytes_timed = pn53x_initiator_transceive_bytes_timed, .initiator_transceive_bits_timed = pn53x_initiator_transceive_bits_timed, .initiator_target_is_present = pn53x_initiator_target_is_present, .target_init = pn53x_target_init, .target_send_bytes = pn53x_target_send_bytes, .target_receive_bytes = pn53x_target_receive_bytes, .target_send_bits = pn53x_target_send_bits, .target_receive_bits = pn53x_target_receive_bits, .device_set_property_bool = pn53x_set_property_bool, .device_set_property_int = pn53x_set_property_int, .get_supported_modulation = pn53x_get_supported_modulation, .get_supported_baud_rate = pn53x_get_supported_baud_rate, .device_get_information_about = pn53x_get_information_about, .abort_command = acr122s_abort_command, .idle = pn53x_idle, /* Even if PN532, PowerDown is not recommended on those devices */ .powerdown = NULL, };
zzyjames55-nfc0805
libnfc/drivers/acr122s.c
C
lgpl
19,165
SUBDIRS = chips buses drivers . # set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) -DSYSCONFDIR='"$(sysconfdir)"' lib_LTLIBRARIES = libnfc.la libnfc_la_SOURCES = \ conf.c \ iso14443-subr.c \ mirror-subr.c \ nfc.c \ nfc-device.c \ nfc-emulation.c \ nfc-internal.c \ target-subr.c \ conf.h \ drivers.h \ iso7816.h \ log.h \ log-internal.h \ mirror-subr.h \ nfc-internal.h \ target-subr.h libnfc_la_LDFLAGS = -no-undefined -version-info 4:0:0 -export-symbols-regex '^nfc_|^iso14443a_|^str_nfc_|pn53x_transceive|pn532_SAMConfiguration|pn53x_read_register|pn53x_write_register' libnfc_la_CFLAGS = @DRIVERS_CFLAGS@ libnfc_la_LIBADD = \ $(top_builddir)/libnfc/chips/libnfcchips.la \ $(top_builddir)/libnfc/buses/libnfcbuses.la \ $(top_builddir)/libnfc/drivers/libnfcdrivers.la if PCSC_ENABLED libnfc_la_CFLAGS += @libpcsclite_CFLAGS@ -DHAVE_PCSC libnfc_la_LIBADD += @libpcsclite_LIBS@ endif if LIBUSB_ENABLED libnfc_la_CFLAGS += @libusb_CFLAGS@ -DHAVE_LIBUSB libnfc_la_LIBADD += @libusb_LIBS@ endif if WITH_LOG libnfc_la_SOURCES += log.c log-internal.c endif EXTRA_DIST = \ CMakeLists.txt
zzyjames55-nfc0805
libnfc/Makefile.am
Makefile
lgpl
1,238
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * * @file mirror-subr.h * @brief Mirror bytes */ #ifndef _LIBNFC_MIRROR_SUBR_H_ # define _LIBNFC_MIRROR_SUBR_H_ # include <stdint.h> # include <nfc/nfc-types.h> uint8_t mirror(uint8_t bt); uint32_t mirror32(uint32_t ui32Bits); uint64_t mirror64(uint64_t ui64Bits); void mirror_uint8_ts(uint8_t *pbts, size_t szLen); #endif // _LIBNFC_MIRROR_SUBR_H_
zzyjames55-nfc0805
libnfc/mirror-subr.h
C
lgpl
1,446
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc.c * @brief NFC library implementation */ /** * @defgroup lib Library initialization/deinitialization * This page details how to initialize and deinitialize libnfc. Initialization * must be performed before using any libnfc functionality, and similarly you * must not call any libnfc functions after deinitialization. */ /** * @defgroup dev NFC Device/Hardware manipulation * The functionality documented below is designed to help with the following * operations: * - Enumerating the NFC devices currently attached to the system * - Opening and closing the chosen device */ /** * @defgroup initiator NFC initiator * This page details how to act as "reader". */ /** * @defgroup target NFC target * This page details how to act as tag (i.e. MIFARE Classic) or NFC target device. */ /** * @defgroup error Error reporting * Most libnfc functions return 0 on success or one of error codes defined on failure. */ /** * @defgroup data Special data accessors * The functionnality documented below allow to access to special data as device name or device connstring. */ /** * @defgroup properties Properties accessors * The functionnality documented below allow to configure parameters and registers. */ /** * @defgroup misc Miscellaneous * */ /** * @defgroup string-converter To-string converters * The functionnality documented below allow to retreive some information in text format. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <nfc/nfc.h> #include "nfc-internal.h" #include "target-subr.h" #include "drivers.h" #if defined (DRIVER_ACR122_PCSC_ENABLED) # include "drivers/acr122_pcsc.h" #endif /* DRIVER_ACR122_PCSC_ENABLED */ #if defined (DRIVER_ACR122_USB_ENABLED) # include "drivers/acr122_usb.h" #endif /* DRIVER_ACR122_USB_ENABLED */ #if defined (DRIVER_ACR122S_ENABLED) # include "drivers/acr122s.h" #endif /* DRIVER_ACR122S_ENABLED */ #if defined (DRIVER_PN53X_USB_ENABLED) # include "drivers/pn53x_usb.h" #endif /* DRIVER_PN53X_USB_ENABLED */ #if defined (DRIVER_ARYGON_ENABLED) # include "drivers/arygon.h" #endif /* DRIVER_ARYGON_ENABLED */ #if defined (DRIVER_PN532_UART_ENABLED) # include "drivers/pn532_uart.h" #endif /* DRIVER_PN532_UART_ENABLED */ #if defined (DRIVER_PN532_SPI_ENABLED) # include "drivers/pn532_spi.h" #endif /* DRIVER_PN532_SPI_ENABLED */ #if defined (DRIVER_PN532_I2C_ENABLED) # include "drivers/pn532_i2c.h" #endif /* DRIVER_PN532_I2C_ENABLED */ #define LOG_CATEGORY "libnfc.general" #define LOG_GROUP NFC_LOG_GROUP_GENERAL struct nfc_driver_list { const struct nfc_driver_list *next; const struct nfc_driver *driver; }; const struct nfc_driver_list *nfc_drivers = NULL; static void nfc_drivers_init(void) { #if defined (DRIVER_PN53X_USB_ENABLED) nfc_register_driver(&pn53x_usb_driver); #endif /* DRIVER_PN53X_USB_ENABLED */ #if defined (DRIVER_ACR122_PCSC_ENABLED) nfc_register_driver(&acr122_pcsc_driver); #endif /* DRIVER_ACR122_PCSC_ENABLED */ #if defined (DRIVER_ACR122_USB_ENABLED) nfc_register_driver(&acr122_usb_driver); #endif /* DRIVER_ACR122_USB_ENABLED */ #if defined (DRIVER_ACR122S_ENABLED) nfc_register_driver(&acr122s_driver); #endif /* DRIVER_ACR122S_ENABLED */ #if defined (DRIVER_PN532_UART_ENABLED) nfc_register_driver(&pn532_uart_driver); #endif /* DRIVER_PN532_UART_ENABLED */ #if defined (DRIVER_PN532_SPI_ENABLED) nfc_register_driver(&pn532_spi_driver); #endif /* DRIVER_PN532_SPI_ENABLED */ #if defined (DRIVER_PN532_I2C_ENABLED) nfc_register_driver(&pn532_i2c_driver); #endif /* DRIVER_PN532_I2C_ENABLED */ #if defined (DRIVER_ARYGON_ENABLED) nfc_register_driver(&arygon_driver); #endif /* DRIVER_ARYGON_ENABLED */ } /** @ingroup lib * @brief Register an NFC device driver with libnfc. * This function registers a driver with libnfc, the caller is responsible of managing the lifetime of the * driver and make sure that any resources associated with the driver are available after registration. * @param pnd Pointer to an NFC device driver to be registered. * @retval NFC_SUCCESS If the driver registration succeeds. */ int nfc_register_driver(const struct nfc_driver *ndr) { if (!ndr) return NFC_EINVARG; struct nfc_driver_list *pndl = (struct nfc_driver_list *)malloc(sizeof(struct nfc_driver_list)); if (!pndl) return NFC_ESOFT; pndl->driver = ndr; pndl->next = nfc_drivers; nfc_drivers = pndl; return NFC_SUCCESS; } /** @ingroup lib * @brief Initialize libnfc. * This function must be called before calling any other libnfc function * @param context Output location for nfc_context */ void nfc_init(nfc_context **context) { *context = nfc_context_new(); if (!*context) { perror("malloc"); return; } if (!nfc_drivers) nfc_drivers_init(); } /** @ingroup lib * @brief Deinitialize libnfc. * Should be called after closing all open devices and before your application terminates. * @param context The context to deinitialize */ void nfc_exit(nfc_context *context) { while (nfc_drivers) { struct nfc_driver_list *pndl = (struct nfc_driver_list *) nfc_drivers; nfc_drivers = pndl->next; free(pndl); } nfc_context_free(context); } /** @ingroup dev * @brief Open a NFC device * @param context The context to operate on. * @param connstring The device connection string if specific device is wanted, \c NULL otherwise * @return Returns pointer to a \a nfc_device struct if successfull; otherwise returns \c NULL value. * * If \e connstring is \c NULL, the first available device from \a nfc_list_devices function is used. * * If \e connstring is set, this function will try to claim the right device using information provided by \e connstring. * * When it has successfully claimed a NFC device, memory is allocated to save the device information. * It will return a pointer to a \a nfc_device struct. * This pointer should be supplied by every next functions of libnfc that should perform an action with this device. * * @note Depending on the desired operation mode, the device needs to be configured by using nfc_initiator_init() or nfc_target_init(), * optionally followed by manual tuning of the parameters if the default parameters are not suiting your goals. */ nfc_device * nfc_open(nfc_context *context, const nfc_connstring connstring) { nfc_device *pnd = NULL; nfc_connstring ncs; if (connstring == NULL) { if (!nfc_list_devices(context, &ncs, 1)) { return NULL; } } else { strncpy(ncs, connstring, sizeof(nfc_connstring)); ncs[sizeof(nfc_connstring) - 1] = '\0'; } // Search through the device list for an available device const struct nfc_driver_list *pndl = nfc_drivers; while (pndl) { const struct nfc_driver *ndr = pndl->driver; // Specific device is requested: using device description if (0 != strncmp(ndr->name, ncs, strlen(ndr->name))) { // Check if connstring driver is usb -> accept any driver *_usb if ((0 != strncmp("usb", ncs, strlen("usb"))) || 0 != strncmp("_usb", ndr->name + (strlen(ndr->name) - 4), 4)) { pndl = pndl->next; continue; } } pnd = ndr->open(context, ncs); // Test if the opening was successful if (pnd == NULL) { if (0 == strncmp("usb", ncs, strlen("usb"))) { // We've to test the other usb drivers before giving up pndl = pndl->next; continue; } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Unable to open \"%s\".", ncs); return NULL; } for (uint32_t i = 0; i > context->user_defined_device_count; i++) { if (strcmp(ncs, context->user_defined_devices[i].connstring) == 0) { // This is a device sets by user, we use the device name given by user strcpy(pnd->name, context->user_defined_devices[i].name); break; } } log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "\"%s\" (%s) has been claimed.", pnd->name, pnd->connstring); return pnd; } // Too bad, no driver can decode connstring log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "No driver available to handle \"%s\".", ncs); return NULL; } /** @ingroup dev * @brief Close from a NFC device * @param pnd \a nfc_device struct pointer that represent currently used device * * Initiator's selected tag is closed and the device, including allocated \a nfc_device struct, is released. */ void nfc_close(nfc_device *pnd) { if (pnd) { // Close, clean up and release the device pnd->driver->close(pnd); } } /** @ingroup dev * @brief Scan for discoverable supported devices (ie. only available for some drivers) * @return Returns the number of devices found. * @param context The context to operate on, or NULL for the default context. * @param connstrings array of \a nfc_connstring. * @param connstrings_len size of the \a connstrings array. * */ size_t nfc_list_devices(nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len) { size_t device_found = 0; #ifdef CONFFILES // Load manually configured devices (from config file and env variables) // TODO From env var... for (uint32_t i = 0; i < context->user_defined_device_count; i++) { if (context->user_defined_devices[i].optional) { // let's make sure the device exists nfc_device *pnd = NULL; #ifdef ENVVARS char *env_log_level = getenv("LIBNFC_LOG_LEVEL"); char *old_env_log_level = NULL; // do it silently if (env_log_level) { if ((old_env_log_level = malloc(strlen(env_log_level) + 1)) == NULL) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to malloc()"); return 0; } strcpy(old_env_log_level, env_log_level); } setenv("LIBNFC_LOG_LEVEL", "0", 1); #endif // ENVVARS pnd = nfc_open(context, context->user_defined_devices[i].connstring); #ifdef ENVVARS if (old_env_log_level) { setenv("LIBNFC_LOG_LEVEL", old_env_log_level, 1); free(old_env_log_level); } else { unsetenv("LIBNFC_LOG_LEVEL"); } #endif // ENVVARS if (pnd) { nfc_close(pnd); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "User device %s found", context->user_defined_devices[i].name); strcpy((char *)(connstrings + device_found), context->user_defined_devices[i].connstring); device_found ++; if (device_found == connstrings_len) break; } } else { // manual choice is not marked as optional so let's take it blindly strcpy((char *)(connstrings + device_found), context->user_defined_devices[i].connstring); device_found++; if (device_found >= connstrings_len) return device_found; } } #endif // CONFFILES // Device auto-detection if (context->allow_autoscan) { const struct nfc_driver_list *pndl = nfc_drivers; while (pndl) { const struct nfc_driver *ndr = pndl->driver; if ((ndr->scan_type == NOT_INTRUSIVE) || ((context->allow_intrusive_scan) && (ndr->scan_type == INTRUSIVE))) { size_t _device_found = ndr->scan(context, connstrings + (device_found), connstrings_len - (device_found)); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%ld device(s) found using %s driver", (unsigned long) _device_found, ndr->name); if (_device_found > 0) { device_found += _device_found; if (device_found == connstrings_len) break; } } // scan_type is INTRUSIVE but not allowed or NOT_AVAILABLE pndl = pndl->next; } } else if (context->user_defined_device_count == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_INFO, "Warning: %s" , "user must specify device(s) manually when autoscan is disabled"); } return device_found; } /** @ingroup properties * @brief Set a device's integer-property value * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param property \a nfc_property which will be set * @param value integer value * * Sets integer property. * * @see nfc_property enum values */ int nfc_device_set_property_int(nfc_device *pnd, const nfc_property property, const int value) { HAL(device_set_property_int, pnd, property, value); } /** @ingroup properties * @brief Set a device's boolean-property value * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param property \a nfc_property which will be set * @param bEnable boolean to activate/disactivate the property * * Configures parameters and registers that control for example timing, * modulation, frame and error handling. There are different categories for * configuring the \e PN53X chip features (handle, activate, infinite and * accept). */ int nfc_device_set_property_bool(nfc_device *pnd, const nfc_property property, const bool bEnable) { HAL(device_set_property_bool, pnd, property, bEnable); } /** @ingroup initiator * @brief Initialize NFC device as initiator (reader) * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * * The NFC device is configured to function as RFID reader. * After initialization it can be used to communicate to passive RFID tags and active NFC devices. * The reader will act as initiator to communicate peer 2 peer (NFCIP) to other active NFC devices. * - Crc is handled by the device (NP_HANDLE_CRC = true) * - Parity is handled the device (NP_HANDLE_PARITY = true) * - Cryto1 cipher is disabled (NP_ACTIVATE_CRYPTO1 = false) * - Easy framing is enabled (NP_EASY_FRAMING = true) * - Auto-switching in ISO14443-4 mode is enabled (NP_AUTO_ISO14443_4 = true) * - Invalid frames are not accepted (NP_ACCEPT_INVALID_FRAMES = false) * - Multiple frames are not accepted (NP_ACCEPT_MULTIPLE_FRAMES = false) * - 14443-A mode is activated (NP_FORCE_ISO14443_A = true) * - speed is set to 106 kbps (NP_FORCE_SPEED_106 = true) * - Let the device try forever to find a target (NP_INFINITE_SELECT = true) * - RF field is shortly dropped (if it was enabled) then activated again */ int nfc_initiator_init(nfc_device *pnd) { int res = 0; // Drop the field for a while if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) return res; // Enable field so more power consuming cards can power themselves up if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true)) < 0) return res; // Let the device try forever to find a target/tag if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return res; // Activate auto ISO14443-4 switching by default if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0) return res; // Force 14443-A mode if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_ISO14443_A, true)) < 0) return res; // Force speed at 106kbps if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_SPEED_106, true)) < 0) return res; // Disallow invalid frame if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) return res; // Disallow multiple frames if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) return res; HAL(initiator_init, pnd); } /** @ingroup initiator * @brief Initialize NFC device as initiator with its secure element initiator (reader) * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * * The NFC device is configured to function as secure element reader. * After initialization it can be used to communicate with the secure element. * @note RF field is desactvated in order to some power */ int nfc_initiator_init_secure_element(nfc_device *pnd) { HAL(initiator_init_secure_element, pnd); } /** @ingroup initiator * @brief Select a passive or emulated tag * @return Returns selected passive target count on success, otherwise returns libnfc's error code (negative value) * * @param pnd \a nfc_device struct pointer that represent currently used device * @param nm desired modulation * @param pbtInitData optional initiator data used for Felica, ISO14443B, Topaz polling or to select a specific UID in ISO14443A. * @param szInitData length of initiator data \a pbtInitData. * @note pbtInitData is used with different kind of data depending on modulation type: * - for an ISO/IEC 14443 type A modulation, pbbInitData contains the UID you want to select; * - for an ISO/IEC 14443 type B modulation, pbbInitData contains Application Family Identifier (AFI) (see ISO/IEC 14443-3); * - for a FeliCa modulation, pbbInitData contains polling payload (see ISO/IEC 18092 11.2.2.5). * * @param[out] pnt \a nfc_target struct pointer which will filled if available * * The NFC device will try to find one available passive tag or emulated tag. * * The chip needs to know with what kind of tag it is dealing with, therefore * the initial modulation and speed (106, 212 or 424 kbps) should be supplied. */ int nfc_initiator_select_passive_target(nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt) { uint8_t abtInit[MAX(12, szInitData)]; size_t szInit; switch (nm.nmt) { case NMT_ISO14443A: iso14443_cascade_uid(pbtInitData, szInitData, abtInit, &szInit); break; case NMT_JEWEL: case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_FELICA: case NMT_DEP: memcpy(abtInit, pbtInitData, szInitData); szInit = szInitData; break; } HAL(initiator_select_passive_target, pnd, nm, abtInit, szInit, pnt); } /** @ingroup initiator * @brief List passive or emulated tags * @return Returns the number of targets found on success, otherwise returns libnfc's error code (negative value) * * @param pnd \a nfc_device struct pointer that represent currently used device * @param nm desired modulation * @param[out] ant array of \a nfc_target that will be filled with targets info * @param szTargets size of \a ant (will be the max targets listed) * * The NFC device will try to find the available passive tags. Some NFC devices * are capable to emulate passive tags. The standards (ISO18092 and ECMA-340) * describe the modulation that can be used for reader to passive * communications. The chip needs to know with what kind of tag it is dealing * with, therefore the initial modulation and speed (106, 212 or 424 kbps) * should be supplied. */ int nfc_initiator_list_passive_targets(nfc_device *pnd, const nfc_modulation nm, nfc_target ant[], const size_t szTargets) { nfc_target nt; size_t szTargetFound = 0; uint8_t *pbtInitData = NULL; size_t szInitDataLen = 0; int res = 0; pnd->last_error = 0; // Let the reader only try once to find a tag if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false)) < 0) { return res; } prepare_initiator_data(nm, &pbtInitData, &szInitDataLen); while (nfc_initiator_select_passive_target(pnd, nm, pbtInitData, szInitDataLen, &nt) > 0) { size_t i; bool seen = false; // Check if we've already seen this tag for (i = 0; i < szTargetFound; i++) { if (memcmp(&(ant[i]), &nt, sizeof(nfc_target)) == 0) { seen = true; } } if (seen) { break; } memcpy(&(ant[szTargetFound]), &nt, sizeof(nfc_target)); szTargetFound++; if (szTargets == szTargetFound) { break; } nfc_initiator_deselect_target(pnd); // deselect has no effect on FeliCa and Jewel cards so we'll stop after one... // ISO/IEC 14443 B' cards are polled at 100% probability so it's not possible to detect correctly two cards at the same time if ((nm.nmt == NMT_FELICA) || (nm.nmt == NMT_JEWEL) || (nm.nmt == NMT_ISO14443BI) || (nm.nmt == NMT_ISO14443B2SR) || (nm.nmt == NMT_ISO14443B2CT)) { break; } } return szTargetFound; } /** @ingroup initiator * @brief Polling for NFC targets * @return Returns polled targets count, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pnmModulations desired modulations * @param szModulations size of \a pnmModulations * @param uiPollNr specifies the number of polling (0x01 – 0xFE: 1 up to 254 polling, 0xFF: Endless polling) * @note one polling is a polling for each desired target type * @param uiPeriod indicates the polling period in units of 150 ms (0x01 – 0x0F: 150ms – 2.25s) * @note e.g. if uiPeriod=10, it will poll each desired target type during 1.5s * @param[out] pnt pointer on \a nfc_target (over)writable struct */ int nfc_initiator_poll_target(nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt) { HAL(initiator_poll_target, pnd, pnmModulations, szModulations, uiPollNr, uiPeriod, pnt); } /** @ingroup initiator * @brief Select a target and request active or passive mode for D.E.P. (Data Exchange Protocol) * @return Returns selected D.E.P targets count on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param ndm desired D.E.P. mode (\a NDM_ACTIVE or \a NDM_PASSIVE for active, respectively passive mode) * @param nbr desired baud rate * @param ndiInitiator pointer \a nfc_dep_info struct that contains \e NFCID3 and \e General \e Bytes to set to the initiator device (optionnal, can be \e NULL) * @param[out] pnt is a \a nfc_target struct pointer where target information will be put. * @param timeout in milliseconds * * The NFC device will try to find an available D.E.P. target. The standards * (ISO18092 and ECMA-340) describe the modulation that can be used for reader * to passive communications. * * @note \a nfc_dep_info will be returned when the target was acquired successfully. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_initiator_select_dep_target(nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) { HAL(initiator_select_dep_target, pnd, ndm, nbr, pndiInitiator, pnt, timeout); } /** @ingroup initiator * @brief Poll a target and request active or passive mode for D.E.P. (Data Exchange Protocol) * @return Returns selected D.E.P targets count on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represent currently used device * @param ndm desired D.E.P. mode (\a NDM_ACTIVE or \a NDM_PASSIVE for active, respectively passive mode) * @param nbr desired baud rate * @param ndiInitiator pointer \a nfc_dep_info struct that contains \e NFCID3 and \e General \e Bytes to set to the initiator device (optionnal, can be \e NULL) * @param[out] pnt is a \a nfc_target struct pointer where target information will be put. * @param timeout in milliseconds * * The NFC device will try to find an available D.E.P. target. The standards * (ISO18092 and ECMA-340) describe the modulation that can be used for reader * to passive communications. * * @note \a nfc_dep_info will be returned when the target was acquired successfully. */ int nfc_initiator_poll_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) { const int period = 300; int remaining_time = timeout; int res; if ((res = nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, true)) < 0) return res; while (remaining_time > 0) { if ((res = nfc_initiator_select_dep_target(pnd, ndm, nbr, pndiInitiator, pnt, period)) < 0) { if (res != NFC_ETIMEOUT) return res; } if (res == 1) return res; remaining_time -= period; } return 0; } /** @ingroup initiator * @brief Deselect a selected passive or emulated tag * @return Returns 0 on success, otherwise returns libnfc's error code (negative value). * @param pnd \a nfc_device struct pointer that represents currently used device * * After selecting and communicating with a passive tag, this function could be * used to deactivate and release the tag. This is very useful when there are * multiple tags available in the field. It is possible to use the \fn * nfc_initiator_select_passive_target() function to select the first available * tag, test it for the available features and support, deselect it and skip to * the next tag until the correct tag is found. */ int nfc_initiator_deselect_target(nfc_device *pnd) { HAL(initiator_deselect_target, pnd); } /** @ingroup initiator * @brief Send data to target then retrieve data from target * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTx contains the length in bytes. * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * @param timeout in milliseconds * * The NFC device (configured as initiator) will transmit the supplied bytes (\a pbtTx) to the target. * It waits for the response and stores the received bytes in the \a pbtRx byte array. * * If \a NP_EASY_FRAMING option is disabled the frames will sent and received in raw mode: \e PN53x will not handle input neither output data. * * The parity bits are handled by the \e PN53x chip. The CRC can be generated automatically or handled manually. * Using this function, frames can be communicated very fast via the NFC initiator to the tag. * * Tests show that on average this way of communicating is much faster than using the regular driver/middle-ware (often supplied by manufacturers). * * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). * * @note When used with MIFARE Classic, NFC_EMFCAUTHFAIL error is returned if authentication command failed. You need to re-select the tag to operate with. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_initiator_transceive_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout) { HAL(initiator_transceive_bytes, pnd, pbtTx, szTx, pbtRx, szRx, timeout) } /** @ingroup initiator * @brief Transceive raw bit-frames to a target * @return Returns received bits count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTxBits contains the length in bits. * * @note For example the REQA (0x26) command (first anti-collision command of * ISO14443-A) must be precise 7 bits long. This is not possible by using * nfc_initiator_transceive_bytes(). With that function you can only * communicate frames that consist of full bytes. When you send a full byte (8 * bits + 1 parity) with the value of REQA (0x26), a tag will simply not * respond. More information about this can be found in the anti-collision * example (\e nfc-anticol). * * @param pbtTxPar parameter contains a byte array of the corresponding parity bits needed to send per byte. * * @note For example if you send the SELECT_ALL (0x93, 0x20) = [ 10010011, * 00100000 ] command, you have to supply the following parity bytes (0x01, * 0x00) to define the correct odd parity bits. This is only an example to * explain how it works, if you just are sending two bytes with ISO14443-A * compliant parity bits you better can use the * nfc_initiator_transceive_bytes() function. * * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * @param[out] pbtRxPar parameter contains a byte array of the corresponding parity bits * * The NFC device (configured as \e initiator) will transmit low-level messages * where only the modulation is handled by the \e PN53x chip. Construction of * the frame (data, CRC and parity) is completely done by libnfc. This can be * very useful for testing purposes. Some protocols (e.g. MIFARE Classic) * require to violate the ISO14443-A standard by sending incorrect parity and * CRC bytes. Using this feature you are able to simulate these frames. */ int nfc_initiator_transceive_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar) { (void)szRx; HAL(initiator_transceive_bits, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar); } /** @ingroup initiator * @brief Send data to target then retrieve data from target * @return Returns received bytes count on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represents currently used device * @param pbtTx contains a byte array of the frame that needs to be transmitted. * @param szTx contains the length in bytes. * @param[out] pbtRx response from the target * @param szRx size of \a pbtRx (Will return NFC_EOVFLOW if RX exceeds this size) * * This function is similar to nfc_initiator_transceive_bytes() with the following differences: * - A precise cycles counter will indicate the number of cycles between emission & reception of frames. * - It only supports mode with \a NP_EASY_FRAMING option disabled. * - Overall communication with the host is heavier and slower. * * Timer control: * By default timer configuration tries to maximize the precision, which also limits the maximum * cycles count before saturation/timeout. * E.g. with PN53x it can count up to 65535 cycles, so about 4.8ms, with a precision of about 73ns. * - If you're ok with the defaults, set *cycles = 0 before calling this function. * - If you need to count more cycles, set *cycles to the maximum you expect but don't forget * you'll loose in precision and it'll take more time before timeout, so don't abuse! * * @warning The configuration option \a NP_EASY_FRAMING must be set to \c false. * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). */ int nfc_initiator_transceive_bytes_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles) { HAL(initiator_transceive_bytes_timed, pnd, pbtTx, szTx, pbtRx, szRx, cycles); } /** @ingroup initiator * @brief Check target presence * @return Returns 0 on success, otherwise returns libnfc's error code. * * This function tests if \a nfc_target is currently present on NFC device. * @warning The target have to be selected before check its presence * @warning To run the test, one or more commands will be sent to target */ int nfc_initiator_target_is_present(nfc_device *pnd, const nfc_target *pnt) { HAL(initiator_target_is_present, pnd, pnt); } /** @ingroup initiator * @brief Transceive raw bit-frames to a target * @return Returns received bits count on success, otherwise returns libnfc's error code * * This function is similar to nfc_initiator_transceive_bits() with the following differences: * - A precise cycles counter will indicate the number of cycles between emission & reception of frames. * - It only supports mode with \a NP_EASY_FRAMING option disabled and CRC must be handled manually. * - Overall communication with the host is heavier and slower. * * Timer control: * By default timer configuration tries to maximize the precision, which also limits the maximum * cycles count before saturation/timeout. * E.g. with PN53x it can count up to 65535 cycles, so about 4.8ms, with a precision of about 73ns. * - If you're ok with the defaults, set *cycles = 0 before calling this function. * - If you need to count more cycles, set *cycles to the maximum you expect but don't forget * you'll loose in precision and it'll take more time before timeout, so don't abuse! * * @warning The configuration option \a NP_EASY_FRAMING must be set to \c false. * @warning The configuration option \a NP_HANDLE_CRC must be set to \c false. * @warning The configuration option \a NP_HANDLE_PARITY must be set to \c true (the default value). */ int nfc_initiator_transceive_bits_timed(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar, uint32_t *cycles) { (void)szRx; HAL(initiator_transceive_bits_timed, pnd, pbtTx, szTxBits, pbtTxPar, pbtRx, pbtRxPar, cycles); } /** @ingroup target * @brief Initialize NFC device as an emulated tag * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pnt pointer to \a nfc_target struct that represents the wanted emulated target * * @note \a pnt can be updated by this function: if you set NBR_UNDEFINED * and/or NDM_UNDEFINED (ie. for DEP mode), these fields will be updated. * * @param[out] pbtRx Rx buffer pointer * @param[out] szRx received bytes count * @param timeout in milliseconds * * This function initializes NFC device in \e target mode in order to emulate a * tag using the specified \a nfc_target_mode_t. * - Crc is handled by the device (NP_HANDLE_CRC = true) * - Parity is handled the device (NP_HANDLE_PARITY = true) * - Cryto1 cipher is disabled (NP_ACTIVATE_CRYPTO1 = false) * - Auto-switching in ISO14443-4 mode is enabled (NP_AUTO_ISO14443_4 = true) * - Easy framing is disabled (NP_EASY_FRAMING = false) * - Invalid frames are not accepted (NP_ACCEPT_INVALID_FRAMES = false) * - Multiple frames are not accepted (NP_ACCEPT_MULTIPLE_FRAMES = false) * - RF field is dropped * * @warning Be aware that this function will wait (hang) until a command is * received that is not part of the anti-collision. The RATS command for * example would wake up the emulator. After this is received, the send and * receive functions can be used. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_init(nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout) { int res = 0; // Disallow invalid frame if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_INVALID_FRAMES, false)) < 0) return res; // Disallow multiple frames if ((res = nfc_device_set_property_bool(pnd, NP_ACCEPT_MULTIPLE_FRAMES, false)) < 0) return res; // Make sure we reset the CRC and parity to chip handling. if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) return res; if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0) return res; // Activate auto ISO14443-4 switching by default if ((res = nfc_device_set_property_bool(pnd, NP_AUTO_ISO14443_4, true)) < 0) return res; // Activate "easy framing" feature by default if ((res = nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) return res; // Deactivate the CRYPTO1 cipher, it may could cause problems when still active if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) return res; // Drop explicitely the field if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) return res; HAL(target_init, pnd, pnt, pbtRx, szRx, timeout); } /** @ingroup dev * @brief Turn NFC device in idle mode * @return Returns 0 on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * * This function switch the device in idle mode. * In initiator mode, the RF field is turned off and the device is set to low power mode (if avaible); * In target mode, the emulation is stoped (no target available from external initiator) and the device is set to low power mode (if avaible). */ int nfc_idle(nfc_device *pnd) { HAL(idle, pnd); } /** @ingroup dev * @brief Abort current running command * @return Returns 0 on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * * Some commands (ie. nfc_target_init()) are blocking functions and will return only in particular conditions (ie. external initiator request). * This function attempt to abort the current running command. * * @note The blocking function (ie. nfc_target_init()) will failed with DEABORT error. */ int nfc_abort_command(nfc_device *pnd) { HAL(abort_command, pnd); } /** @ingroup target * @brief Send bytes and APDU frames * @return Returns sent bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtTx pointer to Tx buffer * @param szTx size of Tx buffer * @param timeout in milliseconds * * This function make the NFC device (configured as \e target) send byte frames * (e.g. APDU responses) to the \e initiator. * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_send_bytes(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout) { HAL(target_send_bytes, pnd, pbtTx, szTx, timeout); } /** @ingroup target * @brief Receive bytes and APDU frames * @return Returns received bytes count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtRx pointer to Rx buffer * @param szRx size of Rx buffer * @param timeout in milliseconds * * This function retrieves bytes frames (e.g. ADPU) sent by the \e initiator to the NFC device (configured as \e target). * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_target_receive_bytes(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, int timeout) { HAL(target_receive_bytes, pnd, pbtRx, szRx, timeout); } /** @ingroup target * @brief Send raw bit-frames * @return Returns sent bits count on success, otherwise returns libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtTx pointer to Tx buffer * @param szTxBits size of Tx buffer * @param pbtTxPar parameter contains a byte array of the corresponding parity bits needed to send per byte. * This function can be used to transmit (raw) bit-frames to the \e initiator * using the specified NFC device (configured as \e target). */ int nfc_target_send_bits(nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar) { HAL(target_send_bits, pnd, pbtTx, szTxBits, pbtTxPar); } /** @ingroup target * @brief Receive bit-frames * @return Returns received bits count on success, otherwise returns libnfc's error code * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pbtRx pointer to Rx buffer * @param szRx size of Rx buffer * @param[out] pbtRxPar parameter contains a byte array of the corresponding parity bits * * This function makes it possible to receive (raw) bit-frames. It returns all * the messages that are stored in the FIFO buffer of the \e PN53x chip. It * does not require to send any frame and thereby could be used to snoop frames * that are transmitted by a nearby \e initiator. @note Check out the * NP_ACCEPT_MULTIPLE_FRAMES configuration option to avoid losing transmitted * frames. */ int nfc_target_receive_bits(nfc_device *pnd, uint8_t *pbtRx, const size_t szRx, uint8_t *pbtRxPar) { HAL(target_receive_bits, pnd, pbtRx, szRx, pbtRxPar); } static struct sErrorMessage { int iErrorCode; const char *pcErrorMsg; } sErrorMessages[] = { /* Chip-level errors (internal errors, RF errors, etc.) */ { NFC_SUCCESS, "Success" }, { NFC_EIO, "Input / Output Error" }, { NFC_EINVARG, "Invalid argument(s)" }, { NFC_EDEVNOTSUPP, "Not Supported by Device" }, { NFC_ENOTSUCHDEV, "No Such Device" }, { NFC_EOVFLOW, "Buffer Overflow" }, { NFC_ETIMEOUT, "Timeout" }, { NFC_EOPABORTED, "Operation Aborted" }, { NFC_ENOTIMPL, "Not (yet) Implemented" }, { NFC_ETGRELEASED, "Target Released" }, { NFC_EMFCAUTHFAIL, "Mifare Authentication Failed" }, { NFC_ERFTRANS, "RF Transmission Error" }, { NFC_ECHIP, "Device's Internal Chip Error" }, }; /** @ingroup error * @brief Return the last error string * @return Returns a string * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_strerror(const nfc_device *pnd) { const char *pcRes = "Unknown error"; size_t i; for (i = 0; i < (sizeof(sErrorMessages) / sizeof(struct sErrorMessage)); i++) { if (sErrorMessages[i].iErrorCode == pnd->last_error) { pcRes = sErrorMessages[i].pcErrorMsg; break; } } return pcRes; } /** @ingroup error * @brief Renders the last error in pcStrErrBuf for a maximum size of szBufLen chars * @return Returns 0 upon success * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pcStrErrBuf a string that contains the last error. * @param szBufLen size of buffer */ int nfc_strerror_r(const nfc_device *pnd, char *pcStrErrBuf, size_t szBufLen) { return (snprintf(pcStrErrBuf, szBufLen, "%s", nfc_strerror(pnd)) < 0) ? -1 : 0; } /** @ingroup error * @brief Display the last error occured on a nfc_device * * @param pnd \a nfc_device struct pointer that represent currently used device * @param pcString a string */ void nfc_perror(const nfc_device *pnd, const char *pcString) { fprintf(stderr, "%s: %s\n", pcString, nfc_strerror(pnd)); } /** @ingroup error * @brief Returns last error occured on a nfc_device * @return Returns an integer that represents to libnfc's error code. * * @param pnd \a nfc_device struct pointer that represent currently used device */ int nfc_device_get_last_error(const nfc_device *pnd) { return pnd->last_error; } /* Special data accessors */ /** @ingroup data * @brief Returns the device name * @return Returns a string with the device name * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_device_get_name(nfc_device *pnd) { return pnd->name; } /** @ingroup data * @brief Returns the device connection string * @return Returns a string with the device connstring * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_device_get_connstring(nfc_device *pnd) { return pnd->connstring; } /** @ingroup data * @brief Get supported modulations. * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param mode \a nfc_mode. * @param supported_mt pointer of \a nfc_modulation_type array. * */ int nfc_device_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) { HAL(get_supported_modulation, pnd, mode, supported_mt); } /** @ingroup data * @brief Get supported baud rates. * @return Returns 0 on success, otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param nmt \a nfc_modulation_type. * @param supported_br pointer of \a nfc_baud_rate array. * */ int nfc_device_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br) { HAL(get_supported_baud_rate, pnd, nmt, supported_br); } /* Misc. functions */ /** @ingroup misc * @brief Returns the library version * @return Returns a string with the library version * * @param pnd \a nfc_device struct pointer that represent currently used device */ const char * nfc_version(void) { #ifdef GIT_REVISION return GIT_REVISION; #else return PACKAGE_VERSION; #endif // GIT_REVISION } /** @ingroup misc * @brief Free buffer allocated by libnfc * * @param pointer on buffer that needs to be freed */ void nfc_free(void *p) { free(p); } /** @ingroup misc * @brief Print information about NFC device * @return Upon successful return, this function returns the number of characters printed (excluding the null byte used to end output to strings), otherwise returns libnfc's error code (negative value) * @param pnd \a nfc_device struct pointer that represent currently used device * @param buf pointer where string will be allocated, then information printed * * @warning *buf must be freed using nfc_free() */ int nfc_device_get_information_about(nfc_device *pnd, char **buf) { HAL(device_get_information_about, pnd, buf); } /** @ingroup string-converter * @brief Convert \a nfc_baud_rate value to string * @return Returns nfc baud rate * @param \a nfc_baud_rate to convert */ const char * str_nfc_baud_rate(const nfc_baud_rate nbr) { switch (nbr) { case NBR_UNDEFINED: return "undefined baud rate"; break; case NBR_106: return "106 kbps"; break; case NBR_212: return "212 kbps"; break; case NBR_424: return "424 kbps"; break; case NBR_847: return "847 kbps"; break; } // Should never go there.. return ""; } /** @ingroup string-converter * @brief Convert \a nfc_modulation_type value to string * @return Returns nfc modulation type * @param \a nfc_modulation_type to convert */ const char * str_nfc_modulation_type(const nfc_modulation_type nmt) { switch (nmt) { case NMT_ISO14443A: return "ISO/IEC 14443A"; break; case NMT_ISO14443B: return "ISO/IEC 14443-4B"; break; case NMT_ISO14443BI: return "ISO/IEC 14443-4B'"; break; case NMT_ISO14443B2CT: return "ISO/IEC 14443-2B ASK CTx"; break; case NMT_ISO14443B2SR: return "ISO/IEC 14443-2B ST SRx"; break; case NMT_FELICA: return "FeliCa"; break; case NMT_JEWEL: return "Innovision Jewel"; break; case NMT_DEP: return "D.E.P."; break; } // Should never go there.. return ""; } /** @ingroup string-converter * @brief Convert \a nfc_modulation_type value to string * @return Upon successful return, this function returns the number of characters printed (excluding the null byte used to end output to strings), otherwise returns libnfc's error code (negative value) * @param nt \a nfc_target struct to print * @param buf pointer where string will be allocated, then nfc target information printed * * @warning *buf must be freed using nfc_free() */ int str_nfc_target(char **buf, const nfc_target *pnt, bool verbose) { *buf = malloc(4096); if (! *buf) return NFC_ESOFT; (*buf)[0] = '\0'; snprint_nfc_target(*buf, 4096, pnt, verbose); return strlen(*buf); }
zzyjames55-nfc0805
libnfc/nfc.c
C
lgpl
49,907
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tarti?re * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Laurent Latil * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file i2c.h * @brief I2C driver header */ #ifndef __NFC_BUS_I2C_H__ # define __NFC_BUS_I2C_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <linux/i2c-dev.h> # include <nfc/nfc-types.h> typedef void *i2c_device; # define INVALID_I2C_BUS (void*)(~1) # define INVALID_I2C_ADDRESS (void*)(~2) i2c_device i2c_open(const char *pcI2C_busName, uint32_t devAddr); void i2c_close(const i2c_device id); ssize_t i2c_read(i2c_device id, uint8_t *pbtRx, const size_t szRx); int i2c_write(i2c_device id, const uint8_t *pbtTx, const size_t szTx); char **i2c_list_ports(void); #endif // __NFC_BUS_I2C_H__
zzyjames55-nfc0805
libnfc/buses/i2c.h
C
lgpl
1,813
# set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) noinst_LTLIBRARIES = libnfcbuses.la libnfcbuses_la_SOURCES = libnfcbuses_la_CFLAGS = -I$(top_srcdir)/libnfc libnfcbuses_la_LIBADD = EXTRA_DIST = if SPI_ENABLED libnfcbuses_la_SOURCES += spi.c spi.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += spi.c spi.h if UART_ENABLED libnfcbuses_la_SOURCES += uart.c uart.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += uart.c uart.h if LIBUSB_ENABLED libnfcbuses_la_SOURCES += usbbus.c usbbus.h libnfcbuses_la_CFLAGS += @libusb_CFLAGS@ libnfcbuses_la_LIBADD += @libusb_LIBS@ endif EXTRA_DIST += usbbus.c usbbus.h if I2C_ENABLED libnfcbuses_la_SOURCES += i2c.c i2c.h libnfcbuses_la_CFLAGS += libnfcbuses_la_LIBADD += endif EXTRA_DIST += i2c.c i2c.h
zzyjames55-nfc0805
libnfc/buses/Makefile.am
Makefile
lgpl
851
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Evgeny Boger * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file spi.h * @brief SPI driver header */ #ifndef __NFC_BUS_SPI_H__ # define __NFC_BUS_SPI_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <linux/spi/spidev.h> # include <nfc/nfc-types.h> // Define shortcut to types to make code more readable typedef void *spi_port; # define INVALID_SPI_PORT (void*)(~1) # define CLAIMED_SPI_PORT (void*)(~2) spi_port spi_open(const char *pcPortName); void spi_close(const spi_port sp); void spi_set_speed(spi_port sp, const uint32_t uiPortSpeed); void spi_set_mode(spi_port sp, const uint32_t uiPortMode); uint32_t spi_get_speed(const spi_port sp); int spi_receive(spi_port sp, uint8_t *pbtRx, const size_t szRx, bool lsb_first); int spi_send(spi_port sp, const uint8_t *pbtTx, const size_t szTx, bool lsb_first); int spi_send_receive(spi_port sp, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, bool lsb_first); char **spi_list_ports(void); #endif // __NFC_BUS_SPI_H__
zzyjames55-nfc0805
libnfc/buses/spi.h
C
lgpl
2,160
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file uart.c * @brief UART driver */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "uart.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <stdlib.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.uart" # if defined(__APPLE__) const char *serial_ports_device_radix[] = { "tty.SLAB_USBtoUART", "tty.usbserial-", NULL }; # elif defined (__FreeBSD__) || defined (__OpenBSD__) const char *serial_ports_device_radix[] = { "cuaU", "cuau", NULL }; # elif defined (__linux__) const char *serial_ports_device_radix[] = { "ttyUSB", "ttyS", "ttyACM", "ttyAMA", "ttyO", NULL }; # else # error "Can't determine serial string for your system" # endif // Work-around to claim uart interface using the c_iflag (software input processing) from the termios struct # define CCLAIMED 0x80000000 struct serial_port_unix { int fd; // Serial port file descriptor struct termios termios_backup; // Terminal info before using the port struct termios termios_new; // Terminal info during the transaction }; #define UART_DATA( X ) ((struct serial_port_unix *) X) void uart_close_ext(const serial_port sp, const bool restore_termios); serial_port uart_open(const char *pcPortName) { struct serial_port_unix *sp = malloc(sizeof(struct serial_port_unix)); if (sp == 0) return INVALID_SERIAL_PORT; sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (sp->fd == -1) { uart_close_ext(sp, false); return INVALID_SERIAL_PORT; } if (tcgetattr(sp->fd, &sp->termios_backup) == -1) { uart_close_ext(sp, false); return INVALID_SERIAL_PORT; } // Make sure the port is not claimed already if (sp->termios_backup.c_iflag & CCLAIMED) { uart_close_ext(sp, false); return CLAIMED_SERIAL_PORT; } // Copy the old terminal info struct sp->termios_new = sp->termios_backup; sp->termios_new.c_cflag = CS8 | CLOCAL | CREAD; sp->termios_new.c_iflag = CCLAIMED | IGNPAR; sp->termios_new.c_oflag = 0; sp->termios_new.c_lflag = 0; sp->termios_new.c_cc[VMIN] = 0; // block until n bytes are received sp->termios_new.c_cc[VTIME] = 0; // block until a timer expires (n * 100 mSec.) if (tcsetattr(sp->fd, TCSANOW, &sp->termios_new) == -1) { uart_close_ext(sp, true); return INVALID_SERIAL_PORT; } return sp; } void uart_flush_input(serial_port sp) { // This line seems to produce absolutely no effect on my system (GNU/Linux 2.6.35) tcflush(UART_DATA(sp)->fd, TCIFLUSH); // So, I wrote this byte-eater // Retrieve the count of the incoming bytes int available_bytes_count = 0; int res; res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); if (res != 0) { return; } if (available_bytes_count == 0) { return; } char *rx = malloc(available_bytes_count); if (!rx) { perror("malloc"); return; } // There is something available, read the data (void)read(UART_DATA(sp)->fd, rx, available_bytes_count); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%d bytes have eatten.", available_bytes_count); free(rx); } void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Serial port speed requested to be set to %d bauds.", uiPortSpeed); // Portability note: on some systems, B9600 != 9600 so we have to do // uint32_t <=> speed_t associations by hand. speed_t stPortSpeed = B9600; switch (uiPortSpeed) { case 9600: stPortSpeed = B9600; break; case 19200: stPortSpeed = B19200; break; case 38400: stPortSpeed = B38400; break; # ifdef B57600 case 57600: stPortSpeed = B57600; break; # endif # ifdef B115200 case 115200: stPortSpeed = B115200; break; # endif # ifdef B230400 case 230400: stPortSpeed = B230400; break; # endif # ifdef B460800 case 460800: stPortSpeed = B460800; break; # endif default: log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to set serial port speed to %d bauds. Speed value must be one of those defined in termios(3).", uiPortSpeed); return; }; // Set port speed (Input and Output) cfsetispeed(&(UART_DATA(sp)->termios_new), stPortSpeed); cfsetospeed(&(UART_DATA(sp)->termios_new), stPortSpeed); if (tcsetattr(UART_DATA(sp)->fd, TCSADRAIN, &(UART_DATA(sp)->termios_new)) == -1) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unable to apply new speed settings."); } } uint32_t uart_get_speed(serial_port sp) { uint32_t uiPortSpeed = 0; switch (cfgetispeed(&UART_DATA(sp)->termios_new)) { case B9600: uiPortSpeed = 9600; break; case B19200: uiPortSpeed = 19200; break; case B38400: uiPortSpeed = 38400; break; # ifdef B57600 case B57600: uiPortSpeed = 57600; break; # endif # ifdef B115200 case B115200: uiPortSpeed = 115200; break; # endif # ifdef B230400 case B230400: uiPortSpeed = 230400; break; # endif # ifdef B460800 case B460800: uiPortSpeed = 460800; break; # endif } return uiPortSpeed; } void uart_close_ext(const serial_port sp, const bool restore_termios) { if (UART_DATA(sp)->fd >= 0) { if (restore_termios) tcsetattr(UART_DATA(sp)->fd, TCSANOW, &UART_DATA(sp)->termios_backup); close(UART_DATA(sp)->fd); } free(sp); } void uart_close(const serial_port sp) { uart_close_ext(sp, true); } /** * @brief Receive data from UART and copy data to \a pbtRx * * @return 0 on success, otherwise driver error code */ int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout) { int iAbortFd = abort_p ? *((int *)abort_p) : 0; int received_bytes_count = 0; int available_bytes_count = 0; const int expected_bytes_count = (int)szRx; int res; fd_set rfds; do { select: // Reset file descriptor FD_ZERO(&rfds); FD_SET(UART_DATA(sp)->fd, &rfds); if (iAbortFd) { FD_SET(iAbortFd, &rfds); } struct timeval timeout_tv; if (timeout > 0) { timeout_tv.tv_sec = (timeout / 1000); timeout_tv.tv_usec = ((timeout % 1000) * 1000); } res = select(MAX(UART_DATA(sp)->fd, iAbortFd) + 1, &rfds, NULL, NULL, timeout ? &timeout_tv : NULL); if ((res < 0) && (EINTR == errno)) { // The system call was interupted by a signal and a signal handler was // run. Restart the interupted system call. goto select; } // Read error if (res < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error: %s", strerror(errno)); return NFC_EIO; } // Read time-out if (res == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Timeout!"); return NFC_ETIMEOUT; } if (FD_ISSET(iAbortFd, &rfds)) { // Abort requested log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "Abort!"); close(iAbortFd); return NFC_EOPABORTED; } // Retrieve the count of the incoming bytes res = ioctl(UART_DATA(sp)->fd, FIONREAD, &available_bytes_count); if (res != 0) { return NFC_EIO; } // There is something available, read the data res = read(UART_DATA(sp)->fd, pbtRx + received_bytes_count, MIN(available_bytes_count, (expected_bytes_count - received_bytes_count))); // Stop if the OS has some troubles reading the data if (res <= 0) { return NFC_EIO; } received_bytes_count += res; } while (expected_bytes_count > received_bytes_count); LOG_HEX(LOG_GROUP, "RX", pbtRx, szRx); return NFC_SUCCESS; } /** * @brief Send \a pbtTx content to UART * * @return 0 on success, otherwise a driver error is returned */ int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout) { (void) timeout; LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); if ((int) szTx == write(UART_DATA(sp)->fd, pbtTx, szTx)) return NFC_SUCCESS; else return NFC_EIO; } char ** uart_list_ports(void) { char **res = malloc(sizeof(char *)); if (!res) { perror("malloc"); return res; } size_t szRes = 1; res[0] = NULL; DIR *dir; if ((dir = opendir("/dev")) == NULL) { perror("opendir error: /dev"); return res; } struct dirent entry; struct dirent *result; while ((readdir_r(dir, &entry, &result) == 0) && (result != NULL)) { #if !defined(__APPLE__) if (!isdigit(entry.d_name[strlen(entry.d_name) - 1])) continue; #endif const char **p = serial_ports_device_radix; while (*p) { if (!strncmp(entry.d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) { perror("malloc"); goto oom; } res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(entry.d_name)))) { perror("malloc"); goto oom; } sprintf(res[szRes - 1], "/dev/%s", entry.d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(dir); return res; }
zzyjames55-nfc0805
libnfc/buses/uart.c
C
lgpl
10,549
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tarti?re * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Laurent Latil * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file i2c.c * @brief I2C driver (implemented / tested for Linux only currently) */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "i2c.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.i2c" # if defined (__linux__) const char *i2c_ports_device_radix[] = { "i2c-", NULL }; # else # error "Can't determine I2C devices standard names for your system" # endif struct i2c_device_unix { int fd; // I2C device file descriptor }; #define I2C_DATA( X ) ((struct i2c_device_unix *) X) /** * @brief Open an I2C device * * @param pcI2C_busName I2C bus device name * @param devAddr address of the I2C device on the bus * @return pointer to the I2C device structure, or INVALID_I2C_BUS, INVALID_I2C_ADDRESS error codes. */ i2c_device i2c_open(const char *pcI2C_busName, uint32_t devAddr) { struct i2c_device_unix *id = malloc(sizeof(struct i2c_device_unix)); if (id == 0) return INVALID_I2C_BUS ; id->fd = open(pcI2C_busName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (id->fd == -1) { perror("Cannot open I2C bus"); i2c_close(id); return INVALID_I2C_BUS ; } if (ioctl(id->fd, I2C_SLAVE, devAddr) < 0) { perror("Cannot select I2C device"); i2c_close(id); return INVALID_I2C_ADDRESS ; } return id; } /** * @brief Close the I2C device * * @param id I2C device to close. */ void i2c_close(const i2c_device id) { if (I2C_DATA(id) ->fd >= 0) { close(I2C_DATA(id) ->fd); } free(id); } /** * @brief Read a frame from the I2C device and copy data to \a pbtRx * * @param id I2C device. * @param pbtRx pointer on buffer used to store data * @param szRx length of the buffer * @return length (in bytes) of read data, or driver error code (negative value) */ ssize_t i2c_read(i2c_device id, uint8_t *pbtRx, const size_t szRx) { ssize_t res; ssize_t recCount; recCount = read(I2C_DATA(id) ->fd, pbtRx, szRx); if (recCount < 0) { res = NFC_EIO; } else { if (recCount < (ssize_t)szRx) { res = NFC_EINVARG; } else { res = recCount; } } return res; } /** * @brief Write a frame to I2C device containing \a pbtTx content * * @param id I2C device. * @param pbtTx pointer on buffer containing data * @param szTx length of the buffer * @return NFC_SUCCESS on success, otherwise driver error code */ int i2c_write(i2c_device id, const uint8_t *pbtTx, const size_t szTx) { LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); ssize_t writeCount; writeCount = write(I2C_DATA(id) ->fd, pbtTx, szTx); if ((const ssize_t) szTx == writeCount) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "wrote %d bytes successfully.", (int)szTx); return NFC_SUCCESS; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Error: wrote only %d bytes (%d expected).", (int)writeCount, (int) szTx); return NFC_EIO; } } /** * @brief Get the path of all I2C bus devices. * * @return array of strings defining the names of all I2C buses available. This array, and each string, are allocated * by this function and must be freed by caller. */ char ** i2c_list_ports(void) { char **res = malloc(sizeof(char *)); if (!res) { perror("malloc"); return res; } size_t szRes = 1; res[0] = NULL; DIR *dir; if ((dir = opendir("/dev")) == NULL) { perror("opendir error: /dev"); return res; } struct dirent entry; struct dirent *result; while ((readdir_r(dir, &entry, &result) == 0) && (result != NULL)) { const char **p = i2c_ports_device_radix; while (*p) { if (!strncmp(entry.d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) { perror("malloc"); goto oom; } res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(entry.d_name)))) { perror("malloc"); goto oom; } sprintf(res[szRes - 1], "/dev/%s", entry.d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(dir); return res; }
zzyjames55-nfc0805
libnfc/buses/i2c.c
C
lgpl
5,624
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file uart.h * @brief UART driver header */ #ifndef __NFC_BUS_UART_H__ # define __NFC_BUS_UART_H__ # include <sys/time.h> # include <stdio.h> # include <string.h> # include <stdlib.h> # include <nfc/nfc-types.h> // Define shortcut to types to make code more readable typedef void *serial_port; # define INVALID_SERIAL_PORT (void*)(~1) # define CLAIMED_SERIAL_PORT (void*)(~2) serial_port uart_open(const char *pcPortName); void uart_close(const serial_port sp); void uart_flush_input(const serial_port sp); void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed); uint32_t uart_get_speed(const serial_port sp); int uart_receive(serial_port sp, uint8_t *pbtRx, const size_t szRx, void *abort_p, int timeout); int uart_send(serial_port sp, const uint8_t *pbtTx, const size_t szTx, int timeout); char **uart_list_ports(void); #endif // __NFC_BUS_UART_H__
zzyjames55-nfc0805
libnfc/buses/uart.h
C
lgpl
1,991
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file usbbus.c * @brief libusb 0.1 driver wrapper */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdlib.h> #include "usbbus.h" #include "log.h" #define LOG_CATEGORY "libnfc.buses.usbbus" #define LOG_GROUP NFC_LOG_GROUP_DRIVER int usb_prepare(void) { static bool usb_initialized = false; if (!usb_initialized) { #ifdef ENVVARS char *env_log_level = getenv("LIBNFC_LOG_LEVEL"); // Set libusb debug only if asked explicitely: // LIBUSB_LOG_LEVEL=12288 (= NFC_LOG_PRIORITY_DEBUG * 2 ^ NFC_LOG_GROUP_LIBUSB) if (env_log_level && (((atoi(env_log_level) >> (NFC_LOG_GROUP_LIBUSB * 2)) & 0x00000003) >= NFC_LOG_PRIORITY_DEBUG)) { setenv("USB_DEBUG", "255", 1); } #endif usb_init(); usb_initialized = true; } int res; // usb_find_busses will find all of the busses on the system. Returns the // number of changes since previous call to this function (total of new // busses and busses removed). if ((res = usb_find_busses()) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to find USB busses (%s)", _usb_strerror(res)); return -1; } // usb_find_devices will find all of the devices on each bus. This should be // called after usb_find_busses. Returns the number of changes since the // previous call to this function (total of new device and devices removed). if ((res = usb_find_devices()) < 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Unable to find USB devices (%s)", _usb_strerror(res)); return -1; } return 0; }
zzyjames55-nfc0805
libnfc/buses/usbbus.c
C
lgpl
2,669
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Evgeny Boger * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file spi.c * @brief SPI driver */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "spi.h" #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/types.h> #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <termios.h> #include <unistd.h> #include <nfc/nfc.h> #include "nfc-internal.h" #define LOG_GROUP NFC_LOG_GROUP_COM #define LOG_CATEGORY "libnfc.bus.spi" # if defined(__APPLE__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # elif defined (__FreeBSD__) || defined (__OpenBSD__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # elif defined (__linux__) const char *spi_ports_device_radix[] = { "spidev", NULL }; # else # error "Can't determine spi port string for your system" # endif struct spi_port_unix { int fd; // Serial port file descriptor //~ struct termios termios_backup; // Terminal info before using the port //~ struct termios termios_new; // Terminal info during the transaction }; #define SPI_DATA( X ) ((struct spi_port_unix *) X) spi_port spi_open(const char *pcPortName) { struct spi_port_unix *sp = malloc(sizeof(struct spi_port_unix)); if (sp == 0) return INVALID_SPI_PORT; sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NONBLOCK); if (sp->fd == -1) { spi_close(sp); return INVALID_SPI_PORT; } return sp; } void spi_set_speed(spi_port sp, const uint32_t uiPortSpeed) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "SPI port speed requested to be set to %d Hz.", uiPortSpeed); int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_WR_MAX_SPEED_HZ, &uiPortSpeed); log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "ret %d", ret); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error setting SPI speed."); } void spi_set_mode(spi_port sp, const uint32_t uiPortMode) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "SPI port mode requested to be set to %d.", uiPortMode); int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_WR_MODE, &uiPortMode); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error setting SPI mode."); } uint32_t spi_get_speed(spi_port sp) { uint32_t uiPortSpeed = 0; int ret; ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_RD_MAX_SPEED_HZ, &uiPortSpeed); if (ret == -1) log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Error reading SPI speed."); return uiPortSpeed; } void spi_close(const spi_port sp) { close(SPI_DATA(sp)->fd); free(sp); } /** * @brief Perform bit reversal on one byte \a x * * @return reversed byte */ static uint8_t bit_reversal(const uint8_t x) { uint8_t ret = x; ret = (((ret & 0xaa) >> 1) | ((ret & 0x55) << 1)); ret = (((ret & 0xcc) >> 2) | ((ret & 0x33) << 2)); ret = (((ret & 0xf0) >> 4) | ((ret & 0x0f) << 4)); return ret; } /** * @brief Send \a pbtTx content to SPI then receive data from SPI and copy data to \a pbtRx. CS line stays active between transfers as well as during transfers. * * @return 0 on success, otherwise a driver error is returned */ int spi_send_receive(spi_port sp, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, bool lsb_first) { size_t transfers = 0; struct spi_ioc_transfer tr[2]; uint8_t *pbtTxLSB = 0; if (szTx) { LOG_HEX(LOG_GROUP, "TX", pbtTx, szTx); if (lsb_first) { pbtTxLSB = malloc(szTx * sizeof(uint8_t)); if (!pbtTxLSB) { return NFC_ESOFT; } size_t i; for (i = 0; i < szTx; ++i) { pbtTxLSB[i] = bit_reversal(pbtTx[i]); } pbtTx = pbtTxLSB; } struct spi_ioc_transfer tr_send = { .tx_buf = (unsigned long) pbtTx, .rx_buf = 0, .len = szTx , .delay_usecs = 0, .speed_hz = 0, .bits_per_word = 0, }; tr[transfers] = tr_send; ++transfers; } if (szRx) { struct spi_ioc_transfer tr_receive = { .tx_buf = 0, .rx_buf = (unsigned long) pbtRx, .len = szRx, .delay_usecs = 0, .speed_hz = 0, .bits_per_word = 0, }; tr[transfers] = tr_receive; ++transfers; } if (transfers) { int ret = ioctl(SPI_DATA(sp)->fd, SPI_IOC_MESSAGE(transfers), tr); if (szTx && lsb_first) { free(pbtTxLSB); } if (ret != (int)(szRx + szTx)) { return NFC_EIO; } // Reverse received bytes if needed if (szRx) { if (lsb_first) { size_t i; for (i = 0; i < szRx; ++i) { pbtRx[i] = bit_reversal(pbtRx[i]); } } LOG_HEX(LOG_GROUP, "RX", pbtRx, szRx); } } return NFC_SUCCESS; } /** * @brief Receive data from SPI and copy data to \a pbtRx * * @return 0 on success, otherwise driver error code */ int spi_receive(spi_port sp, uint8_t *pbtRx, const size_t szRx, bool lsb_first) { return spi_send_receive(sp, 0, 0, pbtRx, szRx, lsb_first); } /** * @brief Send \a pbtTx content to SPI * * @return 0 on success, otherwise a driver error is returned */ int spi_send(spi_port sp, const uint8_t *pbtTx, const size_t szTx, bool lsb_first) { return spi_send_receive(sp, pbtTx, szTx, 0, 0, lsb_first); } char ** spi_list_ports(void) { char **res = malloc(sizeof(char *)); size_t szRes = 1; res[0] = NULL; DIR *pdDir = opendir("/dev"); struct dirent *pdDirEnt; struct dirent entry; struct dirent *result; while ((readdir_r(pdDir, &entry, &result) == 0) && (result != NULL)) { pdDirEnt = &entry; #if !defined(__APPLE__) if (!isdigit(pdDirEnt->d_name[strlen(pdDirEnt->d_name) - 1])) continue; #endif const char **p = spi_ports_device_radix; while (*p) { if (!strncmp(pdDirEnt->d_name, *p, strlen(*p))) { char **res2 = realloc(res, (szRes + 1) * sizeof(char *)); if (!res2) goto oom; res = res2; if (!(res[szRes - 1] = malloc(6 + strlen(pdDirEnt->d_name)))) goto oom; sprintf(res[szRes - 1], "/dev/%s", pdDirEnt->d_name); szRes++; res[szRes - 1] = NULL; } p++; } } oom: closedir(pdDir); return res; }
zzyjames55-nfc0805
libnfc/buses/spi.c
C
lgpl
7,388
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * @file usbbus.h * @brief libusb 0.1 driver header */ #ifndef __NFC_BUS_USB_H__ # define __NFC_BUS_USB_H__ #ifndef _WIN32 // Under POSIX system, we use libusb (>= 0.1.12) #include <usb.h> #define USB_TIMEDOUT ETIMEDOUT #define _usb_strerror( X ) strerror(-X) #else // Under Windows we use libusb-win32 (>= 1.2.5) #include <lusb0_usb.h> #define USB_TIMEDOUT 116 #define _usb_strerror( X ) usb_strerror() #endif #include <stdbool.h> #include <string.h> int usb_prepare(void); #endif // __NFC_BUS_USB_H__
zzyjames55-nfc0805
libnfc/buses/usbbus.h
C
lgpl
1,600
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * Copyright (C) 2013 Alex Lian * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "log-internal.h" #include <stdio.h> #include <stdarg.h> void log_vput_internal(const char *format, va_list args) { vfprintf(stderr, format, args); } void log_put_internal(const char *format, ...) { va_list va; va_start(va, format); vfprintf(stderr, format, va); va_end(va); }
zzyjames55-nfc0805
libnfc/log-internal.c
C
lgpl
1,417
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-emulation.c * @brief Provide a small API to ease emulation in libnfc */ #include <nfc/nfc.h> #include <nfc/nfc-emulation.h> #include "iso7816.h" /** @ingroup emulation * @brief Emulate a target * @return Returns 0 on success, otherwise returns libnfc's error code (negative value). * * @param pnd \a nfc_device struct pointer that represents currently used device * @param emulator \nfc_emulator struct point that handles input/output functions * * If timeout equals to 0, the function blocks indefinitely (until an error is raised or function is completed) * If timeout equals to -1, the default timeout will be used */ int nfc_emulate_target(nfc_device *pnd, struct nfc_emulator *emulator, const int timeout) { uint8_t abtRx[ISO7816_SHORT_R_APDU_MAX_LEN]; uint8_t abtTx[ISO7816_SHORT_C_APDU_MAX_LEN]; int res; if ((res = nfc_target_init(pnd, emulator->target, abtRx, sizeof(abtRx), timeout)) < 0) { return res; } size_t szRx = res; int io_res = res; while (io_res >= 0) { io_res = emulator->state_machine->io(emulator, abtRx, szRx, abtTx, sizeof(abtTx)); if (io_res > 0) { if ((res = nfc_target_send_bytes(pnd, abtTx, io_res, timeout)) < 0) { return res; } } if (io_res >= 0) { if ((res = nfc_target_receive_bytes(pnd, abtRx, sizeof(abtRx), timeout)) < 0) { return res; } szRx = res; } } return (io_res < 0) ? io_res : 0; }
zzyjames55-nfc0805
libnfc/nfc-emulation.c
C
lgpl
2,532
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file nfc-internal.h * @brief Internal defines and macros */ #ifndef __NFC_INTERNAL_H__ #define __NFC_INTERNAL_H__ #include <stdbool.h> #include <err.h> # include <sys/time.h> #include "nfc/nfc.h" #include "log.h" /** * @macro HAL * @brief Execute corresponding driver function if exists. */ #define HAL( FUNCTION, ... ) pnd->last_error = 0; \ if (pnd->driver->FUNCTION) { \ return pnd->driver->FUNCTION( __VA_ARGS__ ); \ } else { \ pnd->last_error = NFC_EDEVNOTSUPP; \ return false; \ } #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif /* * Buffer management macros. * * The following macros ease setting-up and using buffers: * BUFFER_INIT (data, 5); // data -> [ xx, xx, xx, xx, xx ] * BUFFER_SIZE (data); // size -> 0 * BUFFER_APPEND (data, 0x12); // data -> [ 12, xx, xx, xx, xx ] * BUFFER_SIZE (data); // size -> 1 * uint16_t x = 0x3456; // We suppose we are little endian * BUFFER_APPEND_BYTES (data, x, 2); * // data -> [ 12, 56, 34, xx, xx ] * BUFFER_SIZE (data); // size -> 3 * BUFFER_APPEND_LE (data, x, 2, sizeof (x)); * // data -> [ 12, 56, 34, 34, 56 ] * BUFFER_SIZE (data); // size -> 5 */ /* * Initialise a buffer named buffer_name of size bytes. */ #define BUFFER_INIT(buffer_name, size) \ uint8_t buffer_name[size]; \ size_t __##buffer_name##_n = 0 /* * Create a wrapper for an existing buffer. * BEWARE! It eats children! */ #define BUFFER_ALIAS(buffer_name, origin) \ uint8_t *buffer_name = (void *)origin; \ size_t __##buffer_name##_n = 0; #define BUFFER_SIZE(buffer_name) (__##buffer_name##_n) #define BUFFER_CLEAR(buffer_name) (__##buffer_name##_n = 0) /* * Append one byte of data to the buffer buffer_name. */ #define BUFFER_APPEND(buffer_name, data) \ do { \ buffer_name[__##buffer_name##_n++] = data; \ } while (0) /* * Append size bytes of data to the buffer buffer_name. */ #define BUFFER_APPEND_BYTES(buffer_name, data, size) \ do { \ size_t __n = 0; \ while (__n < size) { \ buffer_name[__##buffer_name##_n++] = ((uint8_t *)data)[__n++]; \ } \ } while (0) typedef enum { NOT_INTRUSIVE, INTRUSIVE, NOT_AVAILABLE, } scan_type_enum; struct nfc_driver { const char *name; const scan_type_enum scan_type; size_t (*scan)(const nfc_context *context, nfc_connstring connstrings[], const size_t connstrings_len); struct nfc_device *(*open)(const nfc_context *context, const nfc_connstring connstring); void (*close)(struct nfc_device *pnd); const char *(*strerror)(const struct nfc_device *pnd); int (*initiator_init)(struct nfc_device *pnd); int (*initiator_init_secure_element)(struct nfc_device *pnd); int (*initiator_select_passive_target)(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt); int (*initiator_poll_target)(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t btPeriod, nfc_target *pnt); int (*initiator_select_dep_target)(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); int (*initiator_deselect_target)(struct nfc_device *pnd); int (*initiator_transceive_bytes)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout); int (*initiator_transceive_bits)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); int (*initiator_transceive_bytes_timed)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles); int (*initiator_transceive_bits_timed)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); int (*initiator_target_is_present)(struct nfc_device *pnd, const nfc_target *pnt); int (*target_init)(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRx, int timeout); int (*target_send_bytes)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); int (*target_receive_bytes)(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout); int (*target_send_bits)(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); int (*target_receive_bits)(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar); int (*device_set_property_bool)(struct nfc_device *pnd, const nfc_property property, const bool bEnable); int (*device_set_property_int)(struct nfc_device *pnd, const nfc_property property, const int value); int (*get_supported_modulation)(struct nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int (*get_supported_baud_rate)(struct nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int (*device_get_information_about)(struct nfc_device *pnd, char **buf); int (*abort_command)(struct nfc_device *pnd); int (*idle)(struct nfc_device *pnd); int (*powerdown)(struct nfc_device *pnd); }; # define DEVICE_NAME_LENGTH 256 # define DEVICE_PORT_LENGTH 64 #define MAX_USER_DEFINED_DEVICES 4 struct nfc_user_defined_device { char name[DEVICE_NAME_LENGTH]; nfc_connstring connstring; bool optional; }; /** * @struct nfc_context * @brief NFC library context * Struct which contains internal options, references, pointers, etc. used by library */ struct nfc_context { bool allow_autoscan; bool allow_intrusive_scan; uint32_t log_level; struct nfc_user_defined_device user_defined_devices[MAX_USER_DEFINED_DEVICES]; unsigned int user_defined_device_count; }; nfc_context *nfc_context_new(void); void nfc_context_free(nfc_context *context); /** * @struct nfc_device * @brief NFC device information */ struct nfc_device { const nfc_context *context; const struct nfc_driver *driver; void *driver_data; void *chip_data; /** Device name string, including device wrapper firmware */ char name[DEVICE_NAME_LENGTH]; /** Device connection string */ nfc_connstring connstring; /** Is the CRC automaticly added, checked and removed from the frames */ bool bCrc; /** Does the chip handle parity bits, all parities are handled as data */ bool bPar; /** Should the chip handle frames encapsulation and chaining */ bool bEasyFraming; /** Should the chip switch automatically activate ISO14443-4 when selecting tags supporting it? */ bool bAutoIso14443_4; /** Supported modulation encoded in a byte */ uint8_t btSupportByte; /** Last reported error */ int last_error; }; nfc_device *nfc_device_new(const nfc_context *context, const nfc_connstring connstring); void nfc_device_free(nfc_device *dev); void string_as_boolean(const char *s, bool *value); void iso14443_cascade_uid(const uint8_t abtUID[], const size_t szUID, uint8_t *pbtCascadedUID, size_t *pszCascadedUID); void prepare_initiator_data(const nfc_modulation nm, uint8_t **ppbtInitiatorData, size_t *pszInitiatorData); int connstring_decode(const nfc_connstring connstring, const char *driver_name, const char *bus_name, char **pparam1, char **pparam2); #endif // __NFC_INTERNAL_H__
zzyjames55-nfc0805
libnfc/nfc-internal.h
C
lgpl
8,639
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef __LOG_INTERNAL_H__ #define __LOG_INTERNAL_H__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <stdarg.h> // Internal methods so different platforms can route the logging // Offering both forms of the variadic function // These are implemented in the log_<platform> specific file void log_put_internal(const char *format, ...); void log_vput_internal(const char *format, va_list args); #endif // __LOG_INTERNAL_H__
zzyjames55-nfc0805
libnfc/log-internal.h
C
lgpl
1,536
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file iso7816.h * @brief Defines some macros extracted for ISO/IEC 7816-4 */ #ifndef __LIBNFC_ISO7816_H__ #define __LIBNFC_ISO7816_H__ #define ISO7816_C_APDU_COMMAND_HEADER_LEN 4 #define ISO7816_SHORT_APDU_MAX_DATA_LEN 256 #define ISO7816_SHORT_C_APDU_MAX_OVERHEAD 2 #define ISO7816_SHORT_R_APDU_RESPONSE_TRAILER_LEN 2 #define ISO7816_SHORT_C_APDU_MAX_LEN (ISO7816_C_APDU_COMMAND_HEADER_LEN + ISO7816_SHORT_APDU_MAX_DATA_LEN + ISO7816_SHORT_C_APDU_MAX_OVERHEAD) #define ISO7816_SHORT_R_APDU_MAX_LEN (ISO7816_SHORT_APDU_MAX_DATA_LEN + ISO7816_SHORT_R_APDU_RESPONSE_TRAILER_LEN) #endif /* !__LIBNFC_ISO7816_H__ */
zzyjames55-nfc0805
libnfc/iso7816.h
C
lgpl
1,704
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file drivers.h * @brief Supported drivers header */ #ifndef __NFC_DRIVERS_H__ #define __NFC_DRIVERS_H__ #include <nfc/nfc-types.h> extern const struct nfc_driver_list *nfc_drivers; #endif // __NFC_DRIVERS_H__
zzyjames55-nfc0805
libnfc/drivers.h
C
lgpl
1,305
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef __LOG_H__ #define __LOG_H__ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include "nfc-internal.h" #define NFC_LOG_PRIORITY_NONE 0 #define NFC_LOG_PRIORITY_ERROR 1 #define NFC_LOG_PRIORITY_INFO 2 #define NFC_LOG_PRIORITY_DEBUG 3 #define NFC_LOG_GROUP_GENERAL 1 #define NFC_LOG_GROUP_CONFIG 2 #define NFC_LOG_GROUP_CHIP 3 #define NFC_LOG_GROUP_DRIVER 4 #define NFC_LOG_GROUP_COM 5 #define NFC_LOG_GROUP_LIBUSB 6 /* To enable log only for one (or more) group, you can use this formula: log_level = NFC_LOG_PRIORITY(main) + NFC_LOG_PRIORITY(group) * 2 ^ (NFC_LOG_GROUP(group) * 2) Examples: * Main log level is NONE and only communication group log is set to DEBUG verbosity (for rx/tx trace): LIBNFC_LOG_LEVEL=3072 // 0+3072 * Main log level is ERROR and driver layer log is set to DEBUG level: LIBNFC_LOG_LEVEL=769 // 1+768 * Main log level is ERROR, driver layer is set to INFO and communication is set to DEBUG: LIBNFC_LOG_LEVEL=3585 // 1+512+3072 */ //int log_priority_to_int(const char* priority); const char *log_priority_to_str(const int priority); #if defined LOG # ifndef __has_attribute # define __has_attribute(x) 0 # endif # if __has_attribute(format) || defined(__GNUC__) # define __has_attribute_format 1 # endif void log_init(const nfc_context *context); void log_exit(void); void log_put(const uint8_t group, const char *category, const uint8_t priority, const char *format, ...) # if __has_attribute_format __attribute__((format(printf, 4, 5))) # endif ; #else // No logging #define log_init(nfc_context) ((void) 0) #define log_exit() ((void) 0) #define log_put(group, category, priority, format, ...) do {} while (0) #endif // LOG /** * @macro LOG_HEX * @brief Log a byte-array in hexadecimal format * Max values: pcTag of 121 bytes + ": " + 300 bytes of data+ "\0" => acBuf of 1024 bytes */ # ifdef LOG # define LOG_HEX(group, pcTag, pbtData, szBytes) do { \ size_t __szPos; \ char __acBuf[1024]; \ size_t __szBuf = 0; \ if ((int)szBytes < 0) { \ fprintf (stderr, "%s:%d: Attempt to print %d bytes!\n", __FILE__, __LINE__, (int)szBytes); \ log_put (group, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s:%d: Attempt to print %d bytes!\n", __FILE__, __LINE__, (int)szBytes); \ abort(); \ break; \ } \ snprintf (__acBuf + __szBuf, sizeof(__acBuf) - __szBuf, "%s: ", pcTag); \ __szBuf += strlen (pcTag) + 2; \ for (__szPos=0; (__szPos < (size_t)(szBytes)) && (__szBuf < sizeof(__acBuf)); __szPos++) { \ snprintf (__acBuf + __szBuf, sizeof(__acBuf) - __szBuf, "%02x ",((uint8_t *)(pbtData))[__szPos]); \ __szBuf += 3; \ } \ log_put (group, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", __acBuf); \ } while (0); # else # define LOG_HEX(group, pcTag, pbtData, szBytes) do { \ (void) group; \ (void) pcTag; \ (void) pbtData; \ (void) szBytes; \ } while (0); # endif #endif // __LOG_H__
zzyjames55-nfc0805
libnfc/log.h
C
lgpl
4,109
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn53x.h * @brief PN531, PN532 and PN533 common functions */ #ifndef __NFC_CHIPS_PN53X_H__ # define __NFC_CHIPS_PN53X_H__ # include <nfc/nfc-types.h> # include "pn53x-internal.h" // Registers and symbols masks used to covers parts within a register // PN53X_REG_CIU_TxMode # define SYMBOL_TX_CRC_ENABLE 0x80 # define SYMBOL_TX_SPEED 0x70 // TX_FRAMING bits explanation: // 00 : ISO/IEC 14443A/MIFARE and Passive Communication mode 106 kbit/s // 01 : Active Communication mode // 10 : FeliCa and Passive Communication mode at 212 kbit/s and 424 kbit/s // 11 : ISO/IEC 14443B # define SYMBOL_TX_FRAMING 0x03 // PN53X_REG_Control_switch_rng # define SYMBOL_CURLIMOFF 0x08 /* When set to 1, the 100 mA current limitations is desactivated. */ # define SYMBOL_SIC_SWITCH_EN 0x10 /* When set to logic 1, the SVDD switch is enabled and the SVDD output delivers power to secure IC and internal pads (SIGIN, SIGOUT and P34). */ # define SYMBOL_RANDOM_DATAREADY 0x02 /* When set to logic 1, a new random number is available. */ // PN53X_REG_CIU_RxMode # define SYMBOL_RX_CRC_ENABLE 0x80 # define SYMBOL_RX_SPEED 0x70 # define SYMBOL_RX_NO_ERROR 0x08 # define SYMBOL_RX_MULTIPLE 0x04 // RX_FRAMING follow same scheme than TX_FRAMING # define SYMBOL_RX_FRAMING 0x03 // PN53X_REG_CIU_TxAuto # define SYMBOL_FORCE_100_ASK 0x40 # define SYMBOL_AUTO_WAKE_UP 0x20 # define SYMBOL_INITIAL_RF_ON 0x04 // PN53X_REG_CIU_ManualRCV # define SYMBOL_PARITY_DISABLE 0x10 // PN53X_REG_CIU_TMode # define SYMBOL_TAUTO 0x80 # define SYMBOL_TPRESCALERHI 0x0F // PN53X_REG_CIU_TPrescaler # define SYMBOL_TPRESCALERLO 0xFF // PN53X_REG_CIU_Command # define SYMBOL_COMMAND 0x0F # define SYMBOL_COMMAND_TRANSCEIVE 0xC // PN53X_REG_CIU_Status2 # define SYMBOL_MF_CRYPTO1_ON 0x08 // PN53X_REG_CIU_FIFOLevel # define SYMBOL_FLUSH_BUFFER 0x80 # define SYMBOL_FIFO_LEVEL 0x7F // PN53X_REG_CIU_Control # define SYMBOL_INITIATOR 0x10 # define SYMBOL_RX_LAST_BITS 0x07 // PN53X_REG_CIU_BitFraming # define SYMBOL_START_SEND 0x80 # define SYMBOL_RX_ALIGN 0x70 # define SYMBOL_TX_LAST_BITS 0x07 // PN53X Support Byte flags #define SUPPORT_ISO14443A 0x01 #define SUPPORT_ISO14443B 0x02 #define SUPPORT_ISO18092 0x04 // Internal parameters flags # define PARAM_NONE 0x00 # define PARAM_NAD_USED 0x01 # define PARAM_DID_USED 0x02 # define PARAM_AUTO_ATR_RES 0x04 # define PARAM_AUTO_RATS 0x10 # define PARAM_14443_4_PICC 0x20 /* Only for PN532 */ # define PARAM_NFC_SECURE 0x20 /* Only for PN533 */ # define PARAM_NO_AMBLE 0x40 /* Only for PN532 */ // Radio Field Configure Items // Configuration Data length # define RFCI_FIELD 0x01 // 1 # define RFCI_TIMING 0x02 // 3 # define RFCI_RETRY_DATA 0x04 // 1 # define RFCI_RETRY_SELECT 0x05 // 3 # define RFCI_ANALOG_TYPE_A_106 0x0A // 11 # define RFCI_ANALOG_TYPE_A_212_424 0x0B // 8 # define RFCI_ANALOG_TYPE_B 0x0C // 3 # define RFCI_ANALOG_TYPE_14443_4 0x0D // 9 /** * @enum pn53x_power_mode * @brief PN53x power mode enumeration */ typedef enum { NORMAL, // In that case, there is no power saved but the PN53x reacts as fast as possible on the host controller interface. POWERDOWN, // Only on PN532, need to be wake up to process commands with a long preamble LOWVBAT // Only on PN532, need to be wake up to process commands with a long preamble and SAMConfiguration command } pn53x_power_mode; /** * @enum pn53x_operating_mode * @brief PN53x operatin mode enumeration */ typedef enum { IDLE, INITIATOR, TARGET, } pn53x_operating_mode; /** * @enum pn532_sam_mode * @brief PN532 SAM mode enumeration */ typedef enum { PSM_NORMAL = 0x01, PSM_VIRTUAL_CARD = 0x02, PSM_WIRED_CARD = 0x03, PSM_DUAL_CARD = 0x04 } pn532_sam_mode; /** * @internal * @struct pn53x_io * @brief PN53x I/O structure */ struct pn53x_io { int (*send)(struct nfc_device *pnd, const uint8_t *pbtData, const size_t szData, int timeout); int (*receive)(struct nfc_device *pnd, uint8_t *pbtData, const size_t szDataLen, int timeout); }; /* defines */ #define PN53X_CACHE_REGISTER_MIN_ADDRESS PN53X_REG_CIU_Mode #define PN53X_CACHE_REGISTER_MAX_ADDRESS PN53X_REG_CIU_Coll #define PN53X_CACHE_REGISTER_SIZE ((PN53X_CACHE_REGISTER_MAX_ADDRESS - PN53X_CACHE_REGISTER_MIN_ADDRESS) + 1) /** * @internal * @struct pn53x_data * @brief PN53x data structure */ struct pn53x_data { /** Chip type (PN531, PN532 or PN533) */ pn53x_type type; /** Chip firmware text */ char firmware_text[22]; /** Current power mode */ pn53x_power_mode power_mode; /** Current operating mode */ pn53x_operating_mode operating_mode; /** Current emulated target */ nfc_target *current_target; /** Current sam mode (only applicable for PN532) */ pn532_sam_mode sam_mode; /** PN53x I/O functions stored in struct */ const struct pn53x_io *io; /** Last status byte returned by PN53x */ uint8_t last_status_byte; /** Register cache for REG_CIU_BIT_FRAMING, SYMBOL_TX_LAST_BITS: The last TX bits setting, we need to reset this if it does not apply anymore */ uint8_t ui8TxBits; /** Register cache for SetParameters function. */ uint8_t ui8Parameters; /** Last sent command */ uint8_t last_command; /** Interframe timer correction */ int16_t timer_correction; /** Timer prescaler */ uint16_t timer_prescaler; /** WriteBack cache */ uint8_t wb_data[PN53X_CACHE_REGISTER_SIZE]; uint8_t wb_mask[PN53X_CACHE_REGISTER_SIZE]; bool wb_trigged; /** Command timeout */ int timeout_command; /** ATR timeout */ int timeout_atr; /** Communication timeout */ int timeout_communication; /** Supported modulation type */ nfc_modulation_type *supported_modulation_as_initiator; nfc_modulation_type *supported_modulation_as_target; }; #define CHIP_DATA(pnd) ((struct pn53x_data*)(pnd->chip_data)) /** * @enum pn53x_modulation * @brief NFC modulation enumeration */ typedef enum { /** Undefined modulation */ PM_UNDEFINED = -1, /** ISO14443-A (NXP MIFARE) http://en.wikipedia.org/wiki/MIFARE */ PM_ISO14443A_106 = 0x00, /** JIS X 6319-4 (Sony Felica) http://en.wikipedia.org/wiki/FeliCa */ PM_FELICA_212 = 0x01, /** JIS X 6319-4 (Sony Felica) http://en.wikipedia.org/wiki/FeliCa */ PM_FELICA_424 = 0x02, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531) */ PM_ISO14443B_106 = 0x03, /** Jewel Topaz (Innovision Research & Development) (Not supported by PN531) */ PM_JEWEL_106 = 0x04, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_212 = 0x06, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_424 = 0x07, /** ISO14443-B http://en.wikipedia.org/wiki/ISO/IEC_14443 (Not supported by PN531 nor PN532) */ PM_ISO14443B_847 = 0x08, } pn53x_modulation; /** * @enum pn53x_target_type * @brief NFC target type enumeration */ typedef enum { /** Undefined target type */ PTT_UNDEFINED = -1, /** Generic passive 106 kbps (ISO/IEC14443-4A, mifare, DEP) */ PTT_GENERIC_PASSIVE_106 = 0x00, /** Generic passive 212 kbps (FeliCa, DEP) */ PTT_GENERIC_PASSIVE_212 = 0x01, /** Generic passive 424 kbps (FeliCa, DEP) */ PTT_GENERIC_PASSIVE_424 = 0x02, /** Passive 106 kbps ISO/IEC14443-4B */ PTT_ISO14443_4B_106 = 0x03, /** Innovision Jewel tag */ PTT_JEWEL_106 = 0x04, /** Mifare card */ PTT_MIFARE = 0x10, /** FeliCa 212 kbps card */ PTT_FELICA_212 = 0x11, /** FeliCa 424 kbps card */ PTT_FELICA_424 = 0x12, /** Passive 106 kbps ISO/IEC 14443-4A */ PTT_ISO14443_4A_106 = 0x20, /** Passive 106 kbps ISO/IEC 14443-4B with TCL flag */ PTT_ISO14443_4B_TCL_106 = 0x23, /** DEP passive 106 kbps */ PTT_DEP_PASSIVE_106 = 0x40, /** DEP passive 212 kbps */ PTT_DEP_PASSIVE_212 = 0x41, /** DEP passive 424 kbps */ PTT_DEP_PASSIVE_424 = 0x42, /** DEP active 106 kbps */ PTT_DEP_ACTIVE_106 = 0x80, /** DEP active 212 kbps */ PTT_DEP_ACTIVE_212 = 0x81, /** DEP active 424 kbps */ PTT_DEP_ACTIVE_424 = 0x82, } pn53x_target_type; /** * @enum pn53x_target_mode * @brief PN53x target mode enumeration */ typedef enum { /** Configure the PN53x to accept all initiator mode */ PTM_NORMAL = 0x00, /** Configure the PN53x to accept to be initialized only in passive mode */ PTM_PASSIVE_ONLY = 0x01, /** Configure the PN53x to accept to be initialized only as DEP target */ PTM_DEP_ONLY = 0x02, /** Configure the PN532 to accept to be initialized only as ISO/IEC14443-4 PICC */ PTM_ISO14443_4_PICC_ONLY = 0x04 } pn53x_target_mode; extern const uint8_t pn53x_ack_frame[PN53x_ACK_FRAME__LEN]; extern const uint8_t pn53x_nack_frame[PN53x_ACK_FRAME__LEN]; int pn53x_init(struct nfc_device *pnd); int pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Value, const bool bEnable); int pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits); int pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame); int pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar); int pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData, pn53x_type chip_type, nfc_modulation_type nmt, nfc_target_info *pnti); int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t *ui8Value); int pn53x_write_register(struct nfc_device *pnd, uint16_t ui16Reg, uint8_t ui8SymbolMask, uint8_t ui8Value); int pn53x_decode_firmware_version(struct nfc_device *pnd); int pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value); int pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable); int pn53x_check_communication(struct nfc_device *pnd); int pn53x_idle(struct nfc_device *pnd); // NFC device as Initiator functions int pn53x_initiator_init(struct nfc_device *pnd); int pn532_initiator_init_secure_element(struct nfc_device *pnd); int pn53x_initiator_select_passive_target(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt); int pn53x_initiator_poll_target(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt); int pn53x_initiator_select_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout); int pn53x_initiator_transceive_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar); int pn53x_initiator_transceive_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout); int pn53x_initiator_transceive_bits_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles); int pn53x_initiator_transceive_bytes_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles); int pn53x_initiator_deselect_target(struct nfc_device *pnd); int pn53x_initiator_target_is_present(struct nfc_device *pnd, const nfc_target *pnt); // NFC device as Target functions int pn53x_target_init(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_receive_bits(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar); int pn53x_target_receive_bytes(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout); int pn53x_target_send_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar); int pn53x_target_send_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout); // Error handling functions const char *pn53x_strerror(const struct nfc_device *pnd); // C wrappers for PN53x commands int pn53x_SetParameters(struct nfc_device *pnd, const uint8_t ui8Value); int pn532_SAMConfiguration(struct nfc_device *pnd, const pn532_sam_mode mode, int timeout); int pn53x_PowerDown(struct nfc_device *pnd); int pn53x_InListPassiveTarget(struct nfc_device *pnd, const pn53x_modulation pmInitModulation, const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData, const size_t szInitiatorDataLen, uint8_t *pbtTargetsData, size_t *pszTargetsData, int timeout); int pn53x_InDeselect(struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InRelease(struct nfc_device *pnd, const uint8_t ui8Target); int pn53x_InAutoPoll(struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes, const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets, const int timeout); int pn53x_InJumpForDEP(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const uint8_t *pbtPassiveInitiatorData, const uint8_t *pbtNFCID3i, const uint8_t *pbtGB, const size_t szGB, nfc_target *pnt, const int timeout); int pn53x_TgInitAsTarget(struct nfc_device *pnd, pn53x_target_mode ptm, const uint8_t *pbtMifareParams, const uint8_t *pbtTkt, size_t szTkt, const uint8_t *pbtFeliCaParams, const uint8_t *pbtNFCID3t, const uint8_t *pbtGB, const size_t szGB, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout); // RFConfiguration int pn53x_RFConfiguration__RF_field(struct nfc_device *pnd, bool bEnable); int pn53x_RFConfiguration__Various_timings(struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout); int pn53x_RFConfiguration__MaxRtyCOM(struct nfc_device *pnd, const uint8_t MaxRtyCOM); int pn53x_RFConfiguration__MaxRetries(struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation); // Misc int pn53x_check_ack_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_check_error_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen); int pn53x_build_frame(uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData); int pn53x_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt); int pn53x_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br); int pn53x_get_information_about(nfc_device *pnd, char **pbuf); void *pn53x_data_new(struct nfc_device *pnd, const struct pn53x_io *io); void pn53x_data_free(struct nfc_device *pnd); #endif // __NFC_CHIPS_PN53X_H__
zzyjames55-nfc0805
libnfc/chips/pn53x.h
C
lgpl
17,624
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn53x-internal.h * @brief PN531, PN532 and PN533 defines and compatibility */ #ifndef __PN53X_INTERNAL_H__ #define __PN53X_INTERNAL_H__ #include "log.h" // Miscellaneous #define Diagnose 0x00 #define GetFirmwareVersion 0x02 #define GetGeneralStatus 0x04 #define ReadRegister 0x06 #define WriteRegister 0x08 #define ReadGPIO 0x0C #define WriteGPIO 0x0E #define SetSerialBaudRate 0x10 #define SetParameters 0x12 #define SAMConfiguration 0x14 #define PowerDown 0x16 #define AlparCommandForTDA 0x18 // RC-S360 has another command 0x18 for reset &..? // RF communication #define RFConfiguration 0x32 #define RFRegulationTest 0x58 // Initiator #define InJumpForDEP 0x56 #define InJumpForPSL 0x46 #define InListPassiveTarget 0x4A #define InATR 0x50 #define InPSL 0x4E #define InDataExchange 0x40 #define InCommunicateThru 0x42 #define InQuartetByteExchange 0x38 #define InDeselect 0x44 #define InRelease 0x52 #define InSelect 0x54 #define InActivateDeactivatePaypass 0x48 #define InAutoPoll 0x60 // Target #define TgInitAsTarget 0x8C #define TgSetGeneralBytes 0x92 #define TgGetData 0x86 #define TgSetData 0x8E #define TgSetDataSecure 0x96 #define TgSetMetaData 0x94 #define TgSetMetaDataSecure 0x98 #define TgGetInitiatorCommand 0x88 #define TgResponseToInitiator 0x90 #define TgGetTargetStatus 0x8A /** @note PN53x's normal frame: * * .-- Start * | .-- Packet length * | | .-- Length checksum * | | | .-- Direction (D4 Host to PN, D5 PN to Host) * | | | | .-- Code * | | | | | .-- Packet checksum * | | | | | | .-- Postamble * V | | | | | | * ----- V V V V V V * 00 FF 02 FE D4 02 2A 00 */ /** @note PN53x's extended frame: * * .-- Start * | .-- Fixed to FF to enable extended frame * | | .-- Packet length * | | | .-- Length checksum * | | | | .-- Direction (D4 Host to PN, D5 PN to Host) * | | | | | .-- Code * | | | | | | .-- Packet checksum * | | | | | | | .-- Postamble * V V V | | | | | * ----- ----- ----- V V V V V * 00 FF FF FF 00 02 FE D4 02 2A 00 */ /** * Start bytes, packet length, length checksum, direction, packet checksum and postamble are overhead */ // The TFI is considered part of the overhead # define PN53x_NORMAL_FRAME__DATA_MAX_LEN 254 # define PN53x_NORMAL_FRAME__OVERHEAD 8 # define PN53x_EXTENDED_FRAME__DATA_MAX_LEN 264 # define PN53x_EXTENDED_FRAME__OVERHEAD 11 # define PN53x_ACK_FRAME__LEN 6 typedef struct { uint8_t ui8Code; uint8_t ui8CompatFlags; #ifdef LOG const char *abtCommandText; #endif } pn53x_command; typedef enum { PN53X = 0x00, // Unknown PN53x chip type PN531 = 0x01, PN532 = 0x02, PN533 = 0x04, RCS360 = 0x08 } pn53x_type; #ifndef LOG # define PNCMD( X, Y ) { X , Y } # define PNCMD_TRACE( X ) do {} while(0) #else # define PNCMD( X, Y ) { X , Y, #X } # define PNCMD_TRACE( X ) do { \ for (size_t i=0; i<(sizeof(pn53x_commands)/sizeof(pn53x_command)); i++) { \ if ( X == pn53x_commands[i].ui8Code ) { \ log_put( LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", pn53x_commands[i].abtCommandText ); \ break; \ } \ } \ } while(0) #endif static const pn53x_command pn53x_commands[] = { // Miscellaneous PNCMD(Diagnose, PN531 | PN532 | PN533 | RCS360), PNCMD(GetFirmwareVersion, PN531 | PN532 | PN533 | RCS360), PNCMD(GetGeneralStatus, PN531 | PN532 | PN533 | RCS360), PNCMD(ReadRegister, PN531 | PN532 | PN533 | RCS360), PNCMD(WriteRegister, PN531 | PN532 | PN533 | RCS360), PNCMD(ReadGPIO, PN531 | PN532 | PN533), PNCMD(WriteGPIO, PN531 | PN532 | PN533), PNCMD(SetSerialBaudRate, PN531 | PN532 | PN533), PNCMD(SetParameters, PN531 | PN532 | PN533 | RCS360), PNCMD(SAMConfiguration, PN531 | PN532), PNCMD(PowerDown, PN531 | PN532), PNCMD(AlparCommandForTDA, PN533 | RCS360), // Has another usage on RC-S360... // RF communication PNCMD(RFConfiguration, PN531 | PN532 | PN533 | RCS360), PNCMD(RFRegulationTest, PN531 | PN532 | PN533), // Initiator PNCMD(InJumpForDEP, PN531 | PN532 | PN533 | RCS360), PNCMD(InJumpForPSL, PN531 | PN532 | PN533), PNCMD(InListPassiveTarget, PN531 | PN532 | PN533 | RCS360), PNCMD(InATR, PN531 | PN532 | PN533), PNCMD(InPSL, PN531 | PN532 | PN533), PNCMD(InDataExchange, PN531 | PN532 | PN533), PNCMD(InCommunicateThru, PN531 | PN532 | PN533 | RCS360), PNCMD(InQuartetByteExchange, PN533), PNCMD(InDeselect, PN531 | PN532 | PN533 | RCS360), PNCMD(InRelease, PN531 | PN532 | PN533 | RCS360), PNCMD(InSelect, PN531 | PN532 | PN533), PNCMD(InAutoPoll, PN532), PNCMD(InActivateDeactivatePaypass, PN533), // Target PNCMD(TgInitAsTarget, PN531 | PN532 | PN533), PNCMD(TgSetGeneralBytes, PN531 | PN532 | PN533), PNCMD(TgGetData, PN531 | PN532 | PN533), PNCMD(TgSetData, PN531 | PN532 | PN533), PNCMD(TgSetDataSecure, PN533), PNCMD(TgSetMetaData, PN531 | PN532 | PN533), PNCMD(TgSetMetaDataSecure, PN533), PNCMD(TgGetInitiatorCommand, PN531 | PN532 | PN533), PNCMD(TgResponseToInitiator, PN531 | PN532 | PN533), PNCMD(TgGetTargetStatus, PN531 | PN532 | PN533), }; // SFR part #define _BV( X ) (1 << X) #define P30 0 #define P31 1 #define P32 2 #define P33 3 #define P34 4 #define P35 5 // Registers part #ifdef LOG typedef struct { uint16_t ui16Address; const char *abtRegisterText; const char *abtRegisterDescription; } pn53x_register; # define PNREG( X, Y ) { X , #X, Y } #endif /* LOG */ #ifndef LOG # define PNREG_TRACE( X ) do { \ } while(0) #else # define PNREG_TRACE( X ) do { \ for (size_t i=0; i<(sizeof(pn53x_registers)/sizeof(pn53x_register)); i++) { \ if ( X == pn53x_registers[i].ui16Address ) { \ log_put( LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s (%s)", pn53x_registers[i].abtRegisterText, pn53x_registers[i].abtRegisterDescription ); \ break; \ } \ } \ } while(0) #endif // Register addresses #define PN53X_REG_Control_switch_rng 0x6106 #define PN53X_REG_CIU_Mode 0x6301 #define PN53X_REG_CIU_TxMode 0x6302 #define PN53X_REG_CIU_RxMode 0x6303 #define PN53X_REG_CIU_TxControl 0x6304 #define PN53X_REG_CIU_TxAuto 0x6305 #define PN53X_REG_CIU_TxSel 0x6306 #define PN53X_REG_CIU_RxSel 0x6307 #define PN53X_REG_CIU_RxThreshold 0x6308 #define PN53X_REG_CIU_Demod 0x6309 #define PN53X_REG_CIU_FelNFC1 0x630A #define PN53X_REG_CIU_FelNFC2 0x630B #define PN53X_REG_CIU_MifNFC 0x630C #define PN53X_REG_CIU_ManualRCV 0x630D #define PN53X_REG_CIU_TypeB 0x630E // #define PN53X_REG_- 0x630F // #define PN53X_REG_- 0x6310 #define PN53X_REG_CIU_CRCResultMSB 0x6311 #define PN53X_REG_CIU_CRCResultLSB 0x6312 #define PN53X_REG_CIU_GsNOFF 0x6313 #define PN53X_REG_CIU_ModWidth 0x6314 #define PN53X_REG_CIU_TxBitPhase 0x6315 #define PN53X_REG_CIU_RFCfg 0x6316 #define PN53X_REG_CIU_GsNOn 0x6317 #define PN53X_REG_CIU_CWGsP 0x6318 #define PN53X_REG_CIU_ModGsP 0x6319 #define PN53X_REG_CIU_TMode 0x631A #define PN53X_REG_CIU_TPrescaler 0x631B #define PN53X_REG_CIU_TReloadVal_hi 0x631C #define PN53X_REG_CIU_TReloadVal_lo 0x631D #define PN53X_REG_CIU_TCounterVal_hi 0x631E #define PN53X_REG_CIU_TCounterVal_lo 0x631F // #define PN53X_REG_- 0x6320 #define PN53X_REG_CIU_TestSel1 0x6321 #define PN53X_REG_CIU_TestSel2 0x6322 #define PN53X_REG_CIU_TestPinEn 0x6323 #define PN53X_REG_CIU_TestPinValue 0x6324 #define PN53X_REG_CIU_TestBus 0x6325 #define PN53X_REG_CIU_AutoTest 0x6326 #define PN53X_REG_CIU_Version 0x6327 #define PN53X_REG_CIU_AnalogTest 0x6328 #define PN53X_REG_CIU_TestDAC1 0x6329 #define PN53X_REG_CIU_TestDAC2 0x632A #define PN53X_REG_CIU_TestADC 0x632B // #define PN53X_REG_- 0x632C // #define PN53X_REG_- 0x632D // #define PN53X_REG_- 0x632E #define PN53X_REG_CIU_RFlevelDet 0x632F #define PN53X_REG_CIU_SIC_CLK_en 0x6330 #define PN53X_REG_CIU_Command 0x6331 #define PN53X_REG_CIU_CommIEn 0x6332 #define PN53X_REG_CIU_DivIEn 0x6333 #define PN53X_REG_CIU_CommIrq 0x6334 #define PN53X_REG_CIU_DivIrq 0x6335 #define PN53X_REG_CIU_Error 0x6336 #define PN53X_REG_CIU_Status1 0x6337 #define PN53X_REG_CIU_Status2 0x6338 #define PN53X_REG_CIU_FIFOData 0x6339 #define PN53X_REG_CIU_FIFOLevel 0x633A #define PN53X_REG_CIU_WaterLevel 0x633B #define PN53X_REG_CIU_Control 0x633C #define PN53X_REG_CIU_BitFraming 0x633D #define PN53X_REG_CIU_Coll 0x633E #define PN53X_SFR_P3 0xFFB0 #define PN53X_SFR_P3CFGA 0xFFFC #define PN53X_SFR_P3CFGB 0xFFFD #define PN53X_SFR_P7CFGA 0xFFF4 #define PN53X_SFR_P7CFGB 0xFFF5 #define PN53X_SFR_P7 0xFFF7 /* PN53x specific errors */ #define ETIMEOUT 0x01 #define ECRC 0x02 #define EPARITY 0x03 #define EBITCOUNT 0x04 #define EFRAMING 0x05 #define EBITCOLL 0x06 #define ESMALLBUF 0x07 #define EBUFOVF 0x09 #define ERFTIMEOUT 0x0a #define ERFPROTO 0x0b #define EOVHEAT 0x0d #define EINBUFOVF 0x0e #define EINVPARAM 0x10 #define EDEPUNKCMD 0x12 #define EINVRXFRAM 0x13 #define EMFAUTH 0x14 #define ENSECNOTSUPP 0x18 // PN533 only #define EBCC 0x23 #define EDEPINVSTATE 0x25 #define EOPNOTALL 0x26 #define ECMD 0x27 #define ETGREL 0x29 #define ECID 0x2a #define ECDISCARDED 0x2b #define ENFCID3 0x2c #define EOVCURRENT 0x2d #define ENAD 0x2e #ifdef LOG static const pn53x_register pn53x_registers[] = { PNREG(PN53X_REG_CIU_Mode, "Defines general modes for transmitting and receiving"), PNREG(PN53X_REG_CIU_TxMode, "Defines the transmission data rate and framing during transmission"), PNREG(PN53X_REG_CIU_RxMode, "Defines the transmission data rate and framing during receiving"), PNREG(PN53X_REG_CIU_TxControl, "Controls the logical behaviour of the antenna driver pins TX1 and TX2"), PNREG(PN53X_REG_CIU_TxAuto, "Controls the settings of the antenna driver"), PNREG(PN53X_REG_CIU_TxSel, "Selects the internal sources for the antenna driver"), PNREG(PN53X_REG_CIU_RxSel, "Selects internal receiver settings"), PNREG(PN53X_REG_CIU_RxThreshold, "Selects thresholds for the bit decoder"), PNREG(PN53X_REG_CIU_Demod, "Defines demodulator settings"), PNREG(PN53X_REG_CIU_FelNFC1, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_FelNFC2, "Defines the length of the valid range for the received frame"), PNREG(PN53X_REG_CIU_MifNFC, "Controls the communication in ISO/IEC 14443/MIFARE and NFC target mode at 106 kbit/s"), PNREG(PN53X_REG_CIU_ManualRCV, "Allows manual fine tuning of the internal receiver"), PNREG(PN53X_REG_CIU_TypeB, "Configure the ISO/IEC 14443 type B"), // PNREG (PN53X_REG_-, "Reserved"), // PNREG (PN53X_REG_-, "Reserved"), PNREG(PN53X_REG_CIU_CRCResultMSB, "Shows the actual MSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_CRCResultLSB, "Shows the actual LSB values of the CRC calculation"), PNREG(PN53X_REG_CIU_GsNOFF, "Selects the conductance of the antenna driver pins TX1 and TX2 for load modulation when own RF field is switched OFF"), PNREG(PN53X_REG_CIU_ModWidth, "Controls the setting of the width of the Miller pause"), PNREG(PN53X_REG_CIU_TxBitPhase, "Bit synchronization at 106 kbit/s"), PNREG(PN53X_REG_CIU_RFCfg, "Configures the receiver gain and RF level"), PNREG(PN53X_REG_CIU_GsNOn, "Selects the conductance of the antenna driver pins TX1 and TX2 for modulation, when own RF field is switched ON"), PNREG(PN53X_REG_CIU_CWGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when not in modulation phase"), PNREG(PN53X_REG_CIU_ModGsP, "Selects the conductance of the antenna driver pins TX1 and TX2 when in modulation phase"), PNREG(PN53X_REG_CIU_TMode, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TPrescaler, "Defines settings for the internal timer"), PNREG(PN53X_REG_CIU_TReloadVal_hi, "Describes the 16-bit long timer reload value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TReloadVal_lo, "Describes the 16-bit long timer reload value (Lower 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_hi, "Describes the 16-bit long timer actual value (Higher 8 bits)"), PNREG(PN53X_REG_CIU_TCounterVal_lo, "Describes the 16-bit long timer actual value (Lower 8 bits)"), // PNREG (PN53X_REG_-, "Reserved"), PNREG(PN53X_REG_CIU_TestSel1, "General test signals configuration"), PNREG(PN53X_REG_CIU_TestSel2, "General test signals configuration and PRBS control"), PNREG(PN53X_REG_CIU_TestPinEn, "Enables test signals output on pins."), PNREG(PN53X_REG_CIU_TestPinValue, "Defines the values for the 8-bit parallel bus when it is used as I/O bus"), PNREG(PN53X_REG_CIU_TestBus, "Shows the status of the internal test bus"), PNREG(PN53X_REG_CIU_AutoTest, "Controls the digital self-test"), PNREG(PN53X_REG_CIU_Version, "Shows the CIU version"), PNREG(PN53X_REG_CIU_AnalogTest, "Controls the pins AUX1 and AUX2"), PNREG(PN53X_REG_CIU_TestDAC1, "Defines the test value for the TestDAC1"), PNREG(PN53X_REG_CIU_TestDAC2, "Defines the test value for the TestDAC2"), PNREG(PN53X_REG_CIU_TestADC, "Show the actual value of ADC I and Q"), // PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"), // PNREG (PN53X_REG_-, "Reserved for tests"), PNREG(PN53X_REG_CIU_RFlevelDet, "Power down of the RF level detector"), PNREG(PN53X_REG_CIU_SIC_CLK_en, "Enables the use of secure IC clock on P34 / SIC_CLK"), PNREG(PN53X_REG_CIU_Command, "Starts and stops the command execution"), PNREG(PN53X_REG_CIU_CommIEn, "Control bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_DivIEn, "Controls bits to enable and disable the passing of interrupt requests"), PNREG(PN53X_REG_CIU_CommIrq, "Contains common CIU interrupt request flags"), PNREG(PN53X_REG_CIU_DivIrq, "Contains miscellaneous interrupt request flags"), PNREG(PN53X_REG_CIU_Error, "Error flags showing the error status of the last command executed"), PNREG(PN53X_REG_CIU_Status1, "Contains status flags of the CRC, Interrupt Request System and FIFO buffer"), PNREG(PN53X_REG_CIU_Status2, "Contain status flags of the receiver, transmitter and Data Mode Detector"), PNREG(PN53X_REG_CIU_FIFOData, "In- and output of 64 byte FIFO buffer"), PNREG(PN53X_REG_CIU_FIFOLevel, "Indicates the number of bytes stored in the FIFO"), PNREG(PN53X_REG_CIU_WaterLevel, "Defines the thresholds for FIFO under- and overflow warning"), PNREG(PN53X_REG_CIU_Control, "Contains miscellaneous control bits"), PNREG(PN53X_REG_CIU_BitFraming, "Adjustments for bit oriented frames"), PNREG(PN53X_REG_CIU_Coll, "Defines the first bit collision detected on the RF interface"), // SFR PNREG(PN53X_SFR_P3CFGA, "Port 3 configuration"), PNREG(PN53X_SFR_P3CFGB, "Port 3 configuration"), PNREG(PN53X_SFR_P3, "Port 3 value"), PNREG(PN53X_SFR_P7CFGA, "Port 7 configuration"), PNREG(PN53X_SFR_P7CFGB, "Port 7 configuration"), PNREG(PN53X_SFR_P7, "Port 7 value"), }; #endif #endif /* __PN53X_INTERNAL_H__ */
zzyjames55-nfc0805
libnfc/chips/pn53x-internal.h
C
lgpl
16,012
# set the include path found by configure AM_CPPFLAGS = $(all_includes) $(LIBNFC_CFLAGS) noinst_LTLIBRARIES = libnfcchips.la libnfcchips_la_SOURCES = pn53x.c pn53x.h pn53x-internal.h libnfcchips_la_CFLAGS = -I$(top_srcdir)/libnfc
zzyjames55-nfc0805
libnfc/chips/Makefile.am
Makefile
lgpl
233
/*- * Free/Libre Near Field Communication (NFC) library * * Libnfc historical contributors: * Copyright (C) 2009 Roel Verdult * Copyright (C) 2009-2013 Romuald Conty * Copyright (C) 2010-2012 Romain Tartière * Copyright (C) 2010-2013 Philippe Teuwen * Copyright (C) 2012-2013 Ludovic Rousseau * See AUTHORS file for a more comprehensive list of contributors. * Additional contributors of this file: * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @file pn53x.c * @brief PN531, PN532 and PN533 common functions */ #ifdef HAVE_CONFIG_H # include "config.h" #endif // HAVE_CONFIG_H #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdlib.h> #include "nfc/nfc.h" #include "nfc-internal.h" #include "pn53x.h" #include "pn53x-internal.h" #include "mirror-subr.h" #define LOG_CATEGORY "libnfc.chip.pn53x" #define LOG_GROUP NFC_LOG_GROUP_CHIP const uint8_t pn53x_ack_frame[] = { 0x00, 0x00, 0xff, 0x00, 0xff, 0x00 }; const uint8_t pn53x_nack_frame[] = { 0x00, 0x00, 0xff, 0xff, 0x00, 0x00 }; static const uint8_t pn53x_error_frame[] = { 0x00, 0x00, 0xff, 0x01, 0xff, 0x7f, 0x81, 0x00 }; const nfc_baud_rate pn53x_iso14443a_supported_baud_rates[] = { NBR_106, 0 }; const nfc_baud_rate pn53x_felica_supported_baud_rates[] = { NBR_424, NBR_212, 0 }; const nfc_baud_rate pn53x_dep_supported_baud_rates[] = { NBR_424, NBR_212, NBR_106, 0 }; const nfc_baud_rate pn53x_jewel_supported_baud_rates[] = { NBR_106, 0 }; const nfc_baud_rate pn532_iso14443b_supported_baud_rates[] = { NBR_106, 0 }; const nfc_baud_rate pn533_iso14443b_supported_baud_rates[] = { NBR_847, NBR_424, NBR_212, NBR_106, 0 }; const nfc_modulation_type pn53x_supported_modulation_as_target[] = {NMT_ISO14443A, NMT_FELICA, NMT_DEP, 0}; /* prototypes */ int pn53x_reset_settings(struct nfc_device *pnd); int pn53x_writeback_register(struct nfc_device *pnd); nfc_modulation pn53x_ptt_to_nm(const pn53x_target_type ptt); pn53x_modulation pn53x_nm_to_pm(const nfc_modulation nm); pn53x_target_type pn53x_nm_to_ptt(const nfc_modulation nm); void *pn53x_current_target_new(const struct nfc_device *pnd, const nfc_target *pnt); void pn53x_current_target_free(const struct nfc_device *pnd); bool pn53x_current_target_is(const struct nfc_device *pnd, const nfc_target *pnt); /* implementations */ int pn53x_init(struct nfc_device *pnd) { int res = 0; // GetFirmwareVersion command is used to set PN53x chips type (PN531, PN532 or PN533) if ((res = pn53x_decode_firmware_version(pnd)) < 0) { return res; } if (!CHIP_DATA(pnd)->supported_modulation_as_initiator) { CHIP_DATA(pnd)->supported_modulation_as_initiator = malloc(sizeof(nfc_modulation_type) * 9); if (! CHIP_DATA(pnd)->supported_modulation_as_initiator) return NFC_ESOFT; int nbSupportedModulation = 0; if ((pnd->btSupportByte & SUPPORT_ISO14443A)) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443A; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_FELICA; nbSupportedModulation++; } if (pnd->btSupportByte & SUPPORT_ISO14443B) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_ISO14443B; nbSupportedModulation++; } if (CHIP_DATA(pnd)->type != PN531) { CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_JEWEL; nbSupportedModulation++; } CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = NMT_DEP; nbSupportedModulation++; CHIP_DATA(pnd)->supported_modulation_as_initiator[nbSupportedModulation] = 0; } if (!CHIP_DATA(pnd)->supported_modulation_as_target) { CHIP_DATA(pnd)->supported_modulation_as_target = (nfc_modulation_type *) pn53x_supported_modulation_as_target; } // CRC handling should be enabled by default as declared in nfc_device_new // which is the case by default for pn53x, so nothing to do here // Parity handling should be enabled by default as declared in nfc_device_new // which is the case by default for pn53x, so nothing to do here // We can't read these parameters, so we set a default config by using the SetParameters wrapper // Note: pn53x_SetParameters() will save the sent value in pnd->ui8Parameters cache if ((res = pn53x_SetParameters(pnd, PARAM_AUTO_ATR_RES | PARAM_AUTO_RATS)) < 0) { return res; } if ((res = pn53x_reset_settings(pnd)) < 0) { return res; } return NFC_SUCCESS; } int pn53x_reset_settings(struct nfc_device *pnd) { int res = 0; // Reset the ending transmission bits register, it is unknown what the last tranmission used there CHIP_DATA(pnd)->ui8TxBits = 0; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, 0x00)) < 0) { return res; } // Make sure we reset the CRC and parity to chip handling. if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) return res; if ((res = pn53x_set_property_bool(pnd, NP_HANDLE_PARITY, true)) < 0) return res; // Activate "easy framing" feature by default if ((res = pn53x_set_property_bool(pnd, NP_EASY_FRAMING, true)) < 0) return res; // Deactivate the CRYPTO1 cipher, it may could cause problems when still active if ((res = pn53x_set_property_bool(pnd, NP_ACTIVATE_CRYPTO1, false)) < 0) return res; return NFC_SUCCESS; } int pn53x_transceive(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRxLen, int timeout) { bool mi = false; int res = 0; if (CHIP_DATA(pnd)->wb_trigged) { if ((res = pn53x_writeback_register(pnd)) < 0) { return res; } } PNCMD_TRACE(pbtTx[0]); if (timeout > 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Timeout values: %d", timeout); } else if (timeout == 0) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "No timeout"); } else if (timeout == -1) { timeout = CHIP_DATA(pnd)->timeout_command; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Invalid timeout value: %d", timeout); } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); // Check if receiving buffers are available, if not, replace them if (szRxLen == 0 || !pbtRx) { pbtRx = abtRx; } else { szRx = szRxLen; } // Call the send/receice callback functions of the current driver if ((res = CHIP_DATA(pnd)->io->send(pnd, pbtTx, szTx, timeout)) < 0) { return res; } // Command is sent, we store the command CHIP_DATA(pnd)->last_command = pbtTx[0]; // Handle power mode for PN532 if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) { // PN532 automatically goes into PowerDown mode when TgInitAsTarget command will be sent CHIP_DATA(pnd)->power_mode = POWERDOWN; } if ((res = CHIP_DATA(pnd)->io->receive(pnd, pbtRx, szRx, timeout)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (TgInitAsTarget == pbtTx[0])) { // PN532 automatically wakeup on external RF field CHIP_DATA(pnd)->power_mode = NORMAL; // When TgInitAsTarget reply that means an external RF have waken up the chip } switch (pbtTx[0]) { case PowerDown: case InDataExchange: case InCommunicateThru: case InJumpForPSL: case InPSL: case InATR: case InSelect: case InJumpForDEP: case TgGetData: case TgGetInitiatorCommand: case TgSetData: case TgResponseToInitiator: case TgSetGeneralBytes: case TgSetMetaData: if (pbtRx[0] & 0x80) { abort(); } // NAD detected // if (pbtRx[0] & 0x40) { abort(); } // MI detected mi = pbtRx[0] & 0x40; CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; break; case Diagnose: if (pbtTx[1] == 0x06) { // Diagnose: Card presence detection CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; } else { CHIP_DATA(pnd)->last_status_byte = 0; }; break; case InDeselect: case InRelease: if (CHIP_DATA(pnd)->type == RCS360) { // Error code is in pbtRx[1] but we ignore error code anyway // because other PN53x chips always return 0 on those commands CHIP_DATA(pnd)->last_status_byte = 0; break; } CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; break; case ReadRegister: case WriteRegister: if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by the status byte CHIP_DATA(pnd)->last_status_byte = pbtRx[0] & 0x3f; } else { CHIP_DATA(pnd)->last_status_byte = 0; } break; default: CHIP_DATA(pnd)->last_status_byte = 0; } while (mi) { int res2; uint8_t abtRx2[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; // Send empty command to card if ((res2 = CHIP_DATA(pnd)->io->send(pnd, pbtTx, 2, timeout)) < 0) { return res2; } if ((res2 = CHIP_DATA(pnd)->io->receive(pnd, abtRx2, sizeof(abtRx2), timeout)) < 0) { return res2; } mi = abtRx2[0] & 0x40; if ((size_t)(res + res2 - 1) > szRx) { CHIP_DATA(pnd)->last_status_byte = ESMALLBUF; break; } memcpy(pbtRx + res, abtRx2 + 1, res2 - 1); // Copy last status byte pbtRx[0] = abtRx2[0]; res += res2 - 1; } szRx = (size_t) res; switch (CHIP_DATA(pnd)->last_status_byte) { case 0: res = (int)szRx; break; case ETIMEOUT: case ECRC: case EPARITY: case EBITCOUNT: case EFRAMING: case EBITCOLL: case ERFPROTO: case ERFTIMEOUT: case EDEPUNKCMD: case EDEPINVSTATE: case ENAD: case ENFCID3: case EINVRXFRAM: case EBCC: case ECID: res = NFC_ERFTRANS; break; case ESMALLBUF: case EOVCURRENT: case EBUFOVF: case EOVHEAT: case EINBUFOVF: res = NFC_ECHIP; break; case EINVPARAM: case EOPNOTALL: case ECMD: case ENSECNOTSUPP: res = NFC_EINVARG; break; case ETGREL: case ECDISCARDED: res = NFC_ETGRELEASED; pn53x_current_target_free(pnd); break; case EMFAUTH: // When a MIFARE Classic AUTH fails, the tag is automatically in HALT state res = NFC_EMFCAUTHFAIL; break; default: res = NFC_ECHIP; break; }; if (res < 0) { pnd->last_error = res; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "Chip error: \"%s\" (%02x), returned error: \"%s\" (%d))", pn53x_strerror(pnd), CHIP_DATA(pnd)->last_status_byte, nfc_strerror(pnd), res); } else { pnd->last_error = 0; } return res; } int pn53x_set_parameters(struct nfc_device *pnd, const uint8_t ui8Parameter, const bool bEnable) { uint8_t ui8Value = (bEnable) ? (CHIP_DATA(pnd)->ui8Parameters | ui8Parameter) : (CHIP_DATA(pnd)->ui8Parameters & ~(ui8Parameter)); if (ui8Value != CHIP_DATA(pnd)->ui8Parameters) { return pn53x_SetParameters(pnd, ui8Value); } return NFC_SUCCESS; } int pn53x_set_tx_bits(struct nfc_device *pnd, const uint8_t ui8Bits) { // Test if we need to update the transmission bits register setting if (CHIP_DATA(pnd)->ui8TxBits != ui8Bits) { int res = 0; // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_BitFraming, SYMBOL_TX_LAST_BITS, ui8Bits)) < 0) return res; // Store the new setting CHIP_DATA(pnd)->ui8TxBits = ui8Bits; } return NFC_SUCCESS; } int pn53x_wrap_frame(const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtFrame) { uint8_t btFrame; uint8_t btData; uint32_t uiBitPos; uint32_t uiDataPos = 0; size_t szBitsLeft = szTxBits; size_t szFrameBits = 0; // Make sure we should frame at least something if (szBitsLeft == 0) return NFC_ECHIP; // Handle a short response (1byte) as a special case if (szBitsLeft < 9) { *pbtFrame = *pbtTx; szFrameBits = szTxBits; return szFrameBits; } // We start by calculating the frame length in bits szFrameBits = szTxBits + (szTxBits / 8); // Parse the data bytes and add the parity bits // This is really a sensitive process, mirror the frame bytes and append parity bits // buffer = mirror(frame-byte) + parity + mirror(frame-byte) + parity + ... // split "buffer" up in segments of 8 bits again and mirror them // air-bytes = mirror(buffer-byte) + mirror(buffer-byte) + mirror(buffer-byte) + .. while (true) { // Reset the temporary frame byte; btFrame = 0; for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) { // Copy as much data that fits in the frame byte btData = mirror(pbtTx[uiDataPos]); btFrame |= (btData >> uiBitPos); // Save this frame byte *pbtFrame = mirror(btFrame); // Set the remaining bits of the date in the new frame byte and append the parity bit btFrame = (btData << (8 - uiBitPos)); btFrame |= ((pbtTxPar[uiDataPos] & 0x01) << (7 - uiBitPos)); // Backup the frame bits we have so far pbtFrame++; *pbtFrame = mirror(btFrame); // Increase the data (without parity bit) position uiDataPos++; // Test if we are done if (szBitsLeft < 9) return szFrameBits; szBitsLeft -= 8; } // Every 8 data bytes we lose one frame byte to the parities pbtFrame++; } } int pn53x_unwrap_frame(const uint8_t *pbtFrame, const size_t szFrameBits, uint8_t *pbtRx, uint8_t *pbtRxPar) { uint8_t btFrame; uint8_t btData; uint8_t uiBitPos; uint32_t uiDataPos = 0; uint8_t *pbtFramePos = (uint8_t *) pbtFrame; size_t szBitsLeft = szFrameBits; size_t szRxBits = 0; // Make sure we should frame at least something if (szBitsLeft == 0) return NFC_ECHIP; // Handle a short response (1byte) as a special case if (szBitsLeft < 9) { *pbtRx = *pbtFrame; szRxBits = szFrameBits; return szRxBits; } // Calculate the data length in bits szRxBits = szFrameBits - (szFrameBits / 9); // Parse the frame bytes, remove the parity bits and store them in the parity array // This process is the reverse of WrapFrame(), look there for more info while (true) { for (uiBitPos = 0; uiBitPos < 8; uiBitPos++) { btFrame = mirror(pbtFramePos[uiDataPos]); btData = (btFrame << uiBitPos); btFrame = mirror(pbtFramePos[uiDataPos + 1]); btData |= (btFrame >> (8 - uiBitPos)); pbtRx[uiDataPos] = mirror(btData); if (pbtRxPar != NULL) pbtRxPar[uiDataPos] = ((btFrame >> (7 - uiBitPos)) & 0x01); // Increase the data (without parity bit) position uiDataPos++; // Test if we are done if (szBitsLeft < 9) return szRxBits; szBitsLeft -= 9; } // Every 8 data bytes we lose one frame byte to the parities pbtFramePos++; } } int pn53x_decode_target_data(const uint8_t *pbtRawData, size_t szRawData, pn53x_type type, nfc_modulation_type nmt, nfc_target_info *pnti) { uint8_t szAttribRes; switch (nmt) { case NMT_ISO14443A: // We skip the first byte: its the target number (Tg) pbtRawData++; // Somehow they switched the lower and upper ATQA bytes around for the PN531 chipset if (type == PN531) { pnti->nai.abtAtqa[1] = *(pbtRawData++); pnti->nai.abtAtqa[0] = *(pbtRawData++); } else { pnti->nai.abtAtqa[0] = *(pbtRawData++); pnti->nai.abtAtqa[1] = *(pbtRawData++); } pnti->nai.btSak = *(pbtRawData++); // Copy the NFCID1 pnti->nai.szUidLen = *(pbtRawData++); memcpy(pnti->nai.abtUid, pbtRawData, pnti->nai.szUidLen); pbtRawData += pnti->nai.szUidLen; // Did we received an optional ATS (Smardcard ATR) if (szRawData > (pnti->nai.szUidLen + 5)) { pnti->nai.szAtsLen = ((*(pbtRawData++)) - 1); // In pbtRawData, ATS Length byte is counted in ATS Frame. memcpy(pnti->nai.abtAts, pbtRawData, pnti->nai.szAtsLen); } else { pnti->nai.szAtsLen = 0; } // Strip CT (Cascade Tag) to retrieve and store the _real_ UID // (e.g. 0x8801020304050607 is in fact 0x01020304050607) if ((pnti->nai.szUidLen == 8) && (pnti->nai.abtUid[0] == 0x88)) { pnti->nai.szUidLen = 7; memmove(pnti->nai.abtUid, pnti->nai.abtUid + 1, 7); } else if ((pnti->nai.szUidLen == 12) && (pnti->nai.abtUid[0] == 0x88) && (pnti->nai.abtUid[4] == 0x88)) { pnti->nai.szUidLen = 10; memmove(pnti->nai.abtUid, pnti->nai.abtUid + 1, 3); memmove(pnti->nai.abtUid + 3, pnti->nai.abtUid + 5, 7); } break; case NMT_ISO14443B: // We skip the first byte: its the target number (Tg) pbtRawData++; // Now we are in ATQB, we skip the first ATQB byte always equal to 0x50 pbtRawData++; // Store the PUPI (Pseudo-Unique PICC Identifier) memcpy(pnti->nbi.abtPupi, pbtRawData, 4); pbtRawData += 4; // Store the Application Data memcpy(pnti->nbi.abtApplicationData, pbtRawData, 4); pbtRawData += 4; // Store the Protocol Info memcpy(pnti->nbi.abtProtocolInfo, pbtRawData, 3); pbtRawData += 3; // We leave the ATQB field, we now enter in Card IDentifier szAttribRes = *(pbtRawData++); if (szAttribRes) { pnti->nbi.ui8CardIdentifier = *(pbtRawData++); } break; case NMT_ISO14443BI: // Skip V & T Addresses pbtRawData++; if (*pbtRawData != 0x07) { // 0x07 = REPGEN return NFC_ECHIP; } pbtRawData++; // Store the UID memcpy(pnti->nii.abtDIV, pbtRawData, 4); pbtRawData += 4; pnti->nii.btVerLog = *(pbtRawData++); if (pnti->nii.btVerLog & 0x80) { // Type = long? pnti->nii.btConfig = *(pbtRawData++); if (pnti->nii.btConfig & 0x40) { memcpy(pnti->nii.abtAtr, pbtRawData, szRawData - 8); pnti->nii.szAtrLen = szRawData - 8; } } break; case NMT_ISO14443B2SR: // Store the UID memcpy(pnti->nsi.abtUID, pbtRawData, 8); break; case NMT_ISO14443B2CT: // Store UID LSB memcpy(pnti->nci.abtUID, pbtRawData, 2); pbtRawData += 2; // Store Prod Code & Fab Code pnti->nci.btProdCode = *(pbtRawData++); pnti->nci.btFabCode = *(pbtRawData++); // Store UID MSB memcpy(pnti->nci.abtUID + 2, pbtRawData, 2); break; case NMT_FELICA: // We skip the first byte: its the target number (Tg) pbtRawData++; // Store the mandatory info pnti->nfi.szLen = *(pbtRawData++); pnti->nfi.btResCode = *(pbtRawData++); // Copy the NFCID2t memcpy(pnti->nfi.abtId, pbtRawData, 8); pbtRawData += 8; // Copy the felica padding memcpy(pnti->nfi.abtPad, pbtRawData, 8); pbtRawData += 8; // Test if the System code (SYST_CODE) is available if (pnti->nfi.szLen > 18) { memcpy(pnti->nfi.abtSysCode, pbtRawData, 2); } break; case NMT_JEWEL: // We skip the first byte: its the target number (Tg) pbtRawData++; // Store the mandatory info memcpy(pnti->nji.btSensRes, pbtRawData, 2); pbtRawData += 2; memcpy(pnti->nji.btId, pbtRawData, 4); break; // Should not happend... case NMT_DEP: return NFC_ECHIP; break; } return NFC_SUCCESS; } static int pn53x_ReadRegister(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value) { uint8_t abtCmd[] = { ReadRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff }; uint8_t abtRegValue[2]; size_t szRegValue = sizeof(abtRegValue); int res = 0; PNREG_TRACE(ui16RegisterAddress); if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRegValue, szRegValue, -1)) < 0) { return res; } if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte *ui8Value = abtRegValue[1]; } else { *ui8Value = abtRegValue[0]; } return NFC_SUCCESS; } int pn53x_read_register(struct nfc_device *pnd, uint16_t ui16RegisterAddress, uint8_t *ui8Value) { return pn53x_ReadRegister(pnd, ui16RegisterAddress, ui8Value); } static int pn53x_WriteRegister(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8Value) { uint8_t abtCmd[] = { WriteRegister, ui16RegisterAddress >> 8, ui16RegisterAddress & 0xff, ui8Value }; PNREG_TRACE(ui16RegisterAddress); return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_write_register(struct nfc_device *pnd, const uint16_t ui16RegisterAddress, const uint8_t ui8SymbolMask, const uint8_t ui8Value) { if ((ui16RegisterAddress < PN53X_CACHE_REGISTER_MIN_ADDRESS) || (ui16RegisterAddress > PN53X_CACHE_REGISTER_MAX_ADDRESS)) { // Direct write if (ui8SymbolMask != 0xff) { int res = 0; uint8_t ui8CurrentValue; if ((res = pn53x_read_register(pnd, ui16RegisterAddress, &ui8CurrentValue)) < 0) return res; uint8_t ui8NewValue = ((ui8Value & ui8SymbolMask) | (ui8CurrentValue & (~ui8SymbolMask))); if (ui8NewValue != ui8CurrentValue) { return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8NewValue); } } else { return pn53x_WriteRegister(pnd, ui16RegisterAddress, ui8Value); } } else { // Write-back cache area const int internal_address = ui16RegisterAddress - PN53X_CACHE_REGISTER_MIN_ADDRESS; CHIP_DATA(pnd)->wb_data[internal_address] = (CHIP_DATA(pnd)->wb_data[internal_address] & CHIP_DATA(pnd)->wb_mask[internal_address] & (~ui8SymbolMask)) | (ui8Value & ui8SymbolMask); CHIP_DATA(pnd)->wb_mask[internal_address] = CHIP_DATA(pnd)->wb_mask[internal_address] | ui8SymbolMask; CHIP_DATA(pnd)->wb_trigged = true; } return NFC_SUCCESS; } int pn53x_writeback_register(struct nfc_device *pnd) { int res = 0; // TODO Check at each step (ReadRegister, WriteRegister) if we didn't exceed max supported frame length BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); // First step, it looks for registers to be read before applying the requested mask CHIP_DATA(pnd)->wb_trigged = false; for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) { // This register needs to be read: mask is present but does not cover full data width (ie. mask != 0xff) const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n; BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address >> 8); BUFFER_APPEND(abtReadRegisterCmd, pn53x_register_address & 0xff); } } if (BUFFER_SIZE(abtReadRegisterCmd) > 1) { // It needs to read some registers uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // It transceives the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } size_t i = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte i = 1; } for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if ((CHIP_DATA(pnd)->wb_mask[n]) && (CHIP_DATA(pnd)->wb_mask[n] != 0xff)) { CHIP_DATA(pnd)->wb_data[n] = ((CHIP_DATA(pnd)->wb_data[n] & CHIP_DATA(pnd)->wb_mask[n]) | (abtRes[i] & (~CHIP_DATA(pnd)->wb_mask[n]))); if (CHIP_DATA(pnd)->wb_data[n] != abtRes[i]) { // Requested value is different from read one CHIP_DATA(pnd)->wb_mask[n] = 0xff; // We can now apply whole data bits } else { CHIP_DATA(pnd)->wb_mask[n] = 0x00; // We already have the right value } i++; } } } // Now, the writeback-cache only has masks with 0xff, we can start to WriteRegister BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); for (size_t n = 0; n < PN53X_CACHE_REGISTER_SIZE; n++) { if (CHIP_DATA(pnd)->wb_mask[n] == 0xff) { const uint16_t pn53x_register_address = PN53X_CACHE_REGISTER_MIN_ADDRESS + n; PNREG_TRACE(pn53x_register_address); BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address >> 8); BUFFER_APPEND(abtWriteRegisterCmd, pn53x_register_address & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, CHIP_DATA(pnd)->wb_data[n]); // This register is handled, we reset the mask to prevent CHIP_DATA(pnd)->wb_mask[n] = 0x00; } } if (BUFFER_SIZE(abtWriteRegisterCmd) > 1) { // We need to write some registers if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } } return NFC_SUCCESS; } int pn53x_decode_firmware_version(struct nfc_device *pnd) { const uint8_t abtCmd[] = { GetFirmwareVersion }; uint8_t abtFw[4]; size_t szFwLen = sizeof(abtFw); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtFw, szFwLen, -1)) < 0) { return res; } szFwLen = (size_t) res; // Determine which version of chip it is: PN531 will return only 2 bytes, while others return 4 bytes and have the first to tell the version IC if (szFwLen == 2) { CHIP_DATA(pnd)->type = PN531; } else if (szFwLen == 4) { if (abtFw[0] == 0x32) { // PN532 version IC CHIP_DATA(pnd)->type = PN532; } else if (abtFw[0] == 0x33) { // PN533 version IC if (abtFw[1] == 0x01) { // Sony ROM code CHIP_DATA(pnd)->type = RCS360; } else { CHIP_DATA(pnd)->type = PN533; } } else { // Unknown version IC return NFC_ENOTIMPL; } } else { // Unknown chip return NFC_ENOTIMPL; } // Convert firmware info in text, PN531 gives 2 bytes info, but PN532 and PN533 gives 4 switch (CHIP_DATA(pnd)->type) { case PN531: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN531 v%d.%d", abtFw[0], abtFw[1]); pnd->btSupportByte = SUPPORT_ISO14443A | SUPPORT_ISO18092; break; case PN532: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN532 v%d.%d", abtFw[1], abtFw[2]); pnd->btSupportByte = abtFw[3]; break; case PN533: case RCS360: snprintf(CHIP_DATA(pnd)->firmware_text, sizeof(CHIP_DATA(pnd)->firmware_text), "PN533 v%d.%d", abtFw[1], abtFw[2]); pnd->btSupportByte = abtFw[3]; break; case PN53X: // Could not happend break; } return NFC_SUCCESS; } static uint8_t pn53x_int_to_timeout(const int ms) { uint8_t res = 0; if (ms) { res = 0x10; for (int i = 3280; i > 1; i /= 2) { if (ms > i) break; res--; } } return res; } int pn53x_set_property_int(struct nfc_device *pnd, const nfc_property property, const int value) { switch (property) { case NP_TIMEOUT_COMMAND: CHIP_DATA(pnd)->timeout_command = value; break; case NP_TIMEOUT_ATR: CHIP_DATA(pnd)->timeout_atr = value; return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication)); break; case NP_TIMEOUT_COM: CHIP_DATA(pnd)->timeout_communication = value; return pn53x_RFConfiguration__Various_timings(pnd, pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_atr), pn53x_int_to_timeout(CHIP_DATA(pnd)->timeout_communication)); break; // Following properties are invalid (not integer) case NP_HANDLE_CRC: case NP_HANDLE_PARITY: case NP_ACTIVATE_FIELD: case NP_ACTIVATE_CRYPTO1: case NP_INFINITE_SELECT: case NP_ACCEPT_INVALID_FRAMES: case NP_ACCEPT_MULTIPLE_FRAMES: case NP_AUTO_ISO14443_4: case NP_EASY_FRAMING: case NP_FORCE_ISO14443_A: case NP_FORCE_ISO14443_B: case NP_FORCE_SPEED_106: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_set_property_bool(struct nfc_device *pnd, const nfc_property property, const bool bEnable) { uint8_t btValue; int res = 0; switch (property) { case NP_HANDLE_CRC: // Enable or disable automatic receiving/sending of CRC bytes if (bEnable == pnd->bCrc) { // Nothing to do return NFC_SUCCESS; } // TX and RX are both represented by the symbol 0x80 btValue = (bEnable) ? 0x80 : 0x00; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_CRC_ENABLE, btValue)) < 0) return res; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_CRC_ENABLE, btValue)) < 0) return res; pnd->bCrc = bEnable; return NFC_SUCCESS; break; case NP_HANDLE_PARITY: // Handle parity bit by PN53X chip or parse it as data bit if (bEnable == pnd->bPar) // Nothing to do return NFC_SUCCESS; btValue = (bEnable) ? 0x00 : SYMBOL_PARITY_DISABLE; if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_ManualRCV, SYMBOL_PARITY_DISABLE, btValue)) < 0) return res; pnd->bPar = bEnable; return NFC_SUCCESS; break; case NP_EASY_FRAMING: pnd->bEasyFraming = bEnable; return NFC_SUCCESS; break; case NP_ACTIVATE_FIELD: return pn53x_RFConfiguration__RF_field(pnd, bEnable); break; case NP_ACTIVATE_CRYPTO1: btValue = (bEnable) ? SYMBOL_MF_CRYPTO1_ON : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_Status2, SYMBOL_MF_CRYPTO1_ON, btValue); break; case NP_INFINITE_SELECT: // TODO Made some research around this point: // timings could be tweak better than this, and maybe we can tweak timings // to "gain" a sort-of hardware polling (ie. like PN532 does) return pn53x_RFConfiguration__MaxRetries(pnd, (bEnable) ? 0xff : 0x00, // MxRtyATR, default: active = 0xff, passive = 0x02 (bEnable) ? 0xff : 0x01, // MxRtyPSL, default: 0x01 (bEnable) ? 0xff : 0x02 // MxRtyPassiveActivation, default: 0xff (0x00 leads to problems with PN531) ); break; case NP_ACCEPT_INVALID_FRAMES: btValue = (bEnable) ? SYMBOL_RX_NO_ERROR : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_NO_ERROR, btValue); break; case NP_ACCEPT_MULTIPLE_FRAMES: btValue = (bEnable) ? SYMBOL_RX_MULTIPLE : 0x00; return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_MULTIPLE, btValue); break; case NP_AUTO_ISO14443_4: if (bEnable == pnd->bAutoIso14443_4) // Nothing to do return NFC_SUCCESS; pnd->bAutoIso14443_4 = bEnable; return pn53x_set_parameters(pnd, PARAM_AUTO_RATS, bEnable); break; case NP_FORCE_ISO14443_A: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be in ISO14443-A mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x00)) < 0) { return res; } if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x00)) < 0) { return res; } // Set the PN53X to force 100% ASK Modified miller decoding (default for 14443A cards) return pn53x_write_register(pnd, PN53X_REG_CIU_TxAuto, SYMBOL_FORCE_100_ASK, 0x40); break; case NP_FORCE_ISO14443_B: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be in ISO14443-B mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_FRAMING, 0x03)) < 0) { return res; } return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_FRAMING, 0x03); break; case NP_FORCE_SPEED_106: if (!bEnable) { // Nothing to do return NFC_SUCCESS; } // Force pn53x to be at 106 kbps if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxMode, SYMBOL_TX_SPEED, 0x00)) < 0) { return res; } return pn53x_write_register(pnd, PN53X_REG_CIU_RxMode, SYMBOL_RX_SPEED, 0x00); break; // Following properties are invalid (not boolean) case NP_TIMEOUT_COMMAND: case NP_TIMEOUT_ATR: case NP_TIMEOUT_COM: return NFC_EINVARG; break; } return NFC_EINVARG; } int pn53x_idle(struct nfc_device *pnd) { int res = 0; switch (CHIP_DATA(pnd)->operating_mode) { case TARGET: // InRelease used in target mode stops the target emulation and no more // tag are seen from external initiator if ((res = pn53x_InRelease(pnd, 0)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) { // Use PowerDown to go in "Low VBat" power mode if ((res = pnd->driver->powerdown(pnd)) < 0) { return res; } } break; case INITIATOR: // Use InRelease to go in "Standby mode" if ((res = pn53x_InRelease(pnd, 0)) < 0) { return res; } // Disable RF field to avoid heating if ((res = nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) < 0) { return res; } if ((CHIP_DATA(pnd)->type == PN532) && (pnd->driver->powerdown)) { // Use PowerDown to go in "Low VBat" power mode if ((res = pnd->driver->powerdown(pnd)) < 0) { return res; } } break; case IDLE: // Nothing to do. break; }; // Clear the current nfc_target pn53x_current_target_free(pnd); CHIP_DATA(pnd)->operating_mode = IDLE; return NFC_SUCCESS; } int pn53x_check_communication(struct nfc_device *pnd) { const uint8_t abtCmd[] = { Diagnose, 0x00, 'l', 'i', 'b', 'n', 'f', 'c' }; const uint8_t abtExpectedRx[] = { 0x00, 'l', 'i', 'b', 'n', 'f', 'c' }; uint8_t abtRx[sizeof(abtExpectedRx)]; size_t szRx = sizeof(abtRx); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, 500)) < 0) return res; szRx = (size_t) res; if ((sizeof(abtExpectedRx) == szRx) && (0 == memcmp(abtRx, abtExpectedRx, sizeof(abtExpectedRx)))) return NFC_SUCCESS; return NFC_EIO; } int pn53x_initiator_init(struct nfc_device *pnd) { pn53x_reset_settings(pnd); int res; if (CHIP_DATA(pnd)->sam_mode != PSM_NORMAL) { if ((res = pn532_SAMConfiguration(pnd, PSM_NORMAL, -1)) < 0) { return res; } } // Configure the PN53X to be an Initiator or Reader/Writer if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_Control, SYMBOL_INITIATOR, 0x10)) < 0) return res; CHIP_DATA(pnd)->operating_mode = INITIATOR; return NFC_SUCCESS; } int pn532_initiator_init_secure_element(struct nfc_device *pnd) { return pn532_SAMConfiguration(pnd, PSM_WIRED_CARD, -1); } static int pn53x_initiator_select_passive_target_ext(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt, int timeout) { uint8_t abtTargetsData[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szTargetsData = sizeof(abtTargetsData); int res = 0; if (nm.nmt == NMT_ISO14443BI || nm.nmt == NMT_ISO14443B2SR || nm.nmt == NMT_ISO14443B2CT) { if (CHIP_DATA(pnd)->type == RCS360) { // TODO add support for RC-S360, at the moment it refuses to send raw frames without a first select pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // No native support in InListPassiveTarget so we do discovery by hand if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_ISO14443_B, true)) < 0) { return res; } if ((res = nfc_device_set_property_bool(pnd, NP_FORCE_SPEED_106, true)) < 0) { return res; } if ((res = nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) < 0) { return res; } pnd->bEasyFraming = false; if (nm.nmt == NMT_ISO14443B2SR) { // Some work to do before getting the UID... uint8_t abtInitiate[] = "\x06\x00"; size_t szInitiateLen = 2; uint8_t abtSelect[] = { 0x0e, 0x00 }; uint8_t abtRx[1]; // Getting random Chip_ID if ((res = pn53x_initiator_transceive_bytes(pnd, abtInitiate, szInitiateLen, abtRx, sizeof(abtRx), timeout)) < 0) { return res; } abtSelect[1] = abtRx[0]; if ((res = pn53x_initiator_transceive_bytes(pnd, abtSelect, sizeof(abtSelect), abtRx, sizeof(abtRx), timeout)) < 0) { return res; } szTargetsData = (size_t)res; } else if (nm.nmt == NMT_ISO14443B2CT) { // Some work to do before getting the UID... const uint8_t abtReqt[] = { 0x10 }; // Getting product code / fab code & store it in output buffer after the serial nr we'll obtain later if ((res = pn53x_initiator_transceive_bytes(pnd, abtReqt, sizeof(abtReqt), abtTargetsData + 2, sizeof(abtTargetsData) - 2, timeout)) < 0) { return res; } szTargetsData = (size_t)res; } if ((res = pn53x_initiator_transceive_bytes(pnd, pbtInitData, szInitData, abtTargetsData, sizeof(abtTargetsData), timeout)) < 0) { return res; } szTargetsData = (size_t)res; if (nm.nmt == NMT_ISO14443B2CT) { if (szTargetsData != 2) return 0; // Target is not ISO14443B2CT uint8_t abtRead[] = { 0xC4 }; // Reading UID_MSB (Read address 4) if ((res = pn53x_initiator_transceive_bytes(pnd, abtRead, sizeof(abtRead), abtTargetsData + 4, sizeof(abtTargetsData) - 4, timeout)) < 0) { return res; } szTargetsData = 6; // u16 UID_LSB, u8 prod code, u8 fab code, u16 UID_MSB } if (pnt) { pnt->nm = nm; // Fill the tag info struct with the values corresponding to this init modulation if ((res = pn53x_decode_target_data(abtTargetsData, szTargetsData, CHIP_DATA(pnd)->type, nm.nmt, &(pnt->nti))) < 0) { return res; } } if (nm.nmt == NMT_ISO14443BI) { // Select tag uint8_t abtAttrib[6]; memcpy(abtAttrib, abtTargetsData, sizeof(abtAttrib)); abtAttrib[1] = 0x0f; // ATTRIB if ((res = pn53x_initiator_transceive_bytes(pnd, abtAttrib, sizeof(abtAttrib), NULL, 0, timeout)) < 0) { return res; } szTargetsData = (size_t)res; } return abtTargetsData[0]; } // else: const pn53x_modulation pm = pn53x_nm_to_pm(nm); if (PM_UNDEFINED == pm) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } if ((res = pn53x_InListPassiveTarget(pnd, pm, 1, pbtInitData, szInitData, abtTargetsData, &szTargetsData, timeout)) <= 0) return res; // Is a tag info struct available if (pnt) { pnt->nm = nm; // Fill the tag info struct with the values corresponding to this init modulation if ((res = pn53x_decode_target_data(abtTargetsData + 1, szTargetsData - 1, CHIP_DATA(pnd)->type, nm.nmt, &(pnt->nti))) < 0) { return res; } if (pn53x_current_target_new(pnd, pnt) == NULL) { pnd->last_error = NFC_ESOFT; return pnd->last_error; } } return abtTargetsData[0]; } int pn53x_initiator_select_passive_target(struct nfc_device *pnd, const nfc_modulation nm, const uint8_t *pbtInitData, const size_t szInitData, nfc_target *pnt) { return pn53x_initiator_select_passive_target_ext(pnd, nm, pbtInitData, szInitData, pnt, 0); } int pn53x_initiator_poll_target(struct nfc_device *pnd, const nfc_modulation *pnmModulations, const size_t szModulations, const uint8_t uiPollNr, const uint8_t uiPeriod, nfc_target *pnt) { int res = 0; if (CHIP_DATA(pnd)->type == PN532) { size_t szTargetTypes = 0; pn53x_target_type apttTargetTypes[32]; for (size_t n = 0; n < szModulations; n++) { const pn53x_target_type ptt = pn53x_nm_to_ptt(pnmModulations[n]); if (PTT_UNDEFINED == ptt) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } apttTargetTypes[szTargetTypes] = ptt; if ((pnd->bAutoIso14443_4) && (ptt == PTT_MIFARE)) { // Hack to have ATS apttTargetTypes[szTargetTypes] = PTT_ISO14443_4A_106; szTargetTypes++; apttTargetTypes[szTargetTypes] = PTT_MIFARE; } szTargetTypes++; } nfc_target ntTargets[2]; if ((res = pn53x_InAutoPoll(pnd, apttTargetTypes, szTargetTypes, uiPollNr, uiPeriod, ntTargets, 0)) < 0) return res; switch (res) { case 1: *pnt = ntTargets[0]; return res; break; case 2: *pnt = ntTargets[1]; // We keep the selected one return res; break; default: return NFC_ECHIP; break; } if (pn53x_current_target_new(pnd, pnt) == NULL) { return NFC_ESOFT; } } else { pn53x_set_property_bool(pnd, NP_INFINITE_SELECT, true); // FIXME It does not support DEP targets do { for (size_t p = 0; p < uiPollNr; p++) { for (size_t n = 0; n < szModulations; n++) { uint8_t *pbtInitiatorData; size_t szInitiatorData; prepare_initiator_data(pnmModulations[n], &pbtInitiatorData, &szInitiatorData); const int timeout_ms = uiPeriod * 150; if ((res = pn53x_initiator_select_passive_target_ext(pnd, pnmModulations[n], pbtInitiatorData, szInitiatorData, pnt, timeout_ms)) < 0) { if (pnd->last_error != NFC_ETIMEOUT) { return pnd->last_error; } } else { return res; } } } } while (uiPollNr == 0xff); // uiPollNr==0xff means infinite polling // We reach this point when each listing give no result, we simply have to return 0 return 0; } return NFC_ECHIP; } int pn53x_initiator_select_dep_target(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const nfc_dep_info *pndiInitiator, nfc_target *pnt, const int timeout) { const uint8_t abtPassiveInitiatorData[] = { 0x00, 0xff, 0xff, 0x00, 0x0f }; // Only for 212/424 kpbs: First 4 bytes shall be set like this according to NFCIP-1, last byte is TSN (Time Slot Number) const uint8_t *pbtPassiveInitiatorData = NULL; switch (nbr) { case NBR_212: case NBR_424: // Only use this predefined bytes array when we are at 212/424kbps pbtPassiveInitiatorData = abtPassiveInitiatorData; break; case NBR_106: // Nothing to do break; case NBR_847: case NBR_UNDEFINED: return NFC_EINVARG; break; } pn53x_current_target_free(pnd); int res; if (pndiInitiator) { res = pn53x_InJumpForDEP(pnd, ndm, nbr, pbtPassiveInitiatorData, pndiInitiator->abtNFCID3, pndiInitiator->abtGB, pndiInitiator->szGB, pnt, timeout); } else { res = pn53x_InJumpForDEP(pnd, ndm, nbr, pbtPassiveInitiatorData, NULL, NULL, 0, pnt, timeout); } if (res > 0) { if (pn53x_current_target_new(pnd, pnt) == NULL) { return NFC_ESOFT; } } return res; } int pn53x_initiator_transceive_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar) { int res = 0; size_t szFrameBits = 0; size_t szFrameBytes = 0; size_t szRxBits = 0; uint8_t ui8rcc; uint8_t ui8Bits = 0; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN] = { InCommunicateThru }; // Check if we should prepare the parity bits ourself if (!pnd->bPar) { // Convert data with parity to a frame if ((res = pn53x_wrap_frame(pbtTx, szTxBits, pbtTxPar, abtCmd + 1)) < 0) return res; szFrameBits = res; } else { szFrameBits = szTxBits; } // Retrieve the leading bits ui8Bits = szFrameBits % 8; // Get the amount of frame bytes + optional (1 byte if there are leading bits) szFrameBytes = (szFrameBits / 8) + ((ui8Bits == 0) ? 0 : 1); // When the parity is handled before us, we just copy the data if (pnd->bPar) memcpy(abtCmd + 1, pbtTx, szFrameBytes); // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_set_tx_bits(pnd, ui8Bits)) < 0) return res; // Send the frame to the PN53X chip and get the answer // We have to give the amount of bytes + (the command byte 0x42) uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); if ((res = pn53x_transceive(pnd, abtCmd, szFrameBytes + 1, abtRx, szRx, -1)) < 0) return res; szRx = (size_t) res; // Get the last bit-count that is stored in the received byte if ((res = pn53x_read_register(pnd, PN53X_REG_CIU_Control, &ui8rcc)) < 0) return res; ui8Bits = ui8rcc & SYMBOL_RX_LAST_BITS; // Recover the real frame length in bits szFrameBits = ((szRx - 1 - ((ui8Bits == 0) ? 0 : 1)) * 8) + ui8Bits; if (pbtRx != NULL) { // Ignore the status byte from the PN53X here, it was checked earlier in pn53x_transceive() // Check if we should recover the parity bits ourself if (!pnd->bPar) { // Unwrap the response frame if ((res = pn53x_unwrap_frame(abtRx + 1, szFrameBits, pbtRx, pbtRxPar)) < 0) return res; szRxBits = res; } else { // Save the received bits szRxBits = szFrameBits; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx - 1); } } // Everything went successful return szRxBits; } int pn53x_initiator_transceive_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, int timeout) { size_t szExtraTxLen; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int res = 0; // We can not just send bytes without parity if while the PN53X expects we handled them if (!pnd->bPar) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Copy the data into the command frame if (pnd->bEasyFraming) { abtCmd[0] = InDataExchange; abtCmd[1] = 1; /* target number */ memcpy(abtCmd + 2, pbtTx, szTx); szExtraTxLen = 2; } else { abtCmd[0] = InCommunicateThru; memcpy(abtCmd + 1, pbtTx, szTx); szExtraTxLen = 1; } // To transfer command frames bytes we can not have any leading bits, reset this to zero if ((res = pn53x_set_tx_bits(pnd, 0)) < 0) { pnd->last_error = res; return pnd->last_error; } // Send the frame to the PN53X chip and get the answer // We have to give the amount of bytes + (the two command bytes 0xD4, 0x42) uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; if ((res = pn53x_transceive(pnd, abtCmd, szTx + szExtraTxLen, abtRx, sizeof(abtRx), timeout)) < 0) { pnd->last_error = res; return pnd->last_error; } const size_t szRxLen = (size_t)res - 1; if (pbtRx != NULL) { if (szRxLen > szRx) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Buffer size is too short: %" PRIuPTR " available(s), %" PRIuPTR " needed", szRx, szRxLen); return NFC_EOVFLOW; } // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRxLen); } // Everything went successful, we return received bytes count return szRxLen; } static void __pn53x_init_timer(struct nfc_device *pnd, const uint32_t max_cycles) { // The prescaler will dictate what will be the precision and // the largest delay to measure before saturation. Some examples: // prescaler = 0 => precision: ~73ns timer saturates at ~5ms // prescaler = 1 => precision: ~221ns timer saturates at ~15ms // prescaler = 2 => precision: ~369ns timer saturates at ~25ms // prescaler = 10 => precision: ~1.5us timer saturates at ~100ms if (max_cycles > 0xFFFF) { CHIP_DATA(pnd)->timer_prescaler = ((max_cycles / 0xFFFF) - 1) / 2; } else { CHIP_DATA(pnd)->timer_prescaler = 0; } uint16_t reloadval = 0xFFFF; // Initialize timer pn53x_write_register(pnd, PN53X_REG_CIU_TMode, 0xFF, SYMBOL_TAUTO | ((CHIP_DATA(pnd)->timer_prescaler >> 8) & SYMBOL_TPRESCALERHI)); pn53x_write_register(pnd, PN53X_REG_CIU_TPrescaler, 0xFF, (CHIP_DATA(pnd)->timer_prescaler & SYMBOL_TPRESCALERLO)); pn53x_write_register(pnd, PN53X_REG_CIU_TReloadVal_hi, 0xFF, (reloadval >> 8) & 0xFF); pn53x_write_register(pnd, PN53X_REG_CIU_TReloadVal_lo, 0xFF, reloadval & 0xFF); } static uint32_t __pn53x_get_timer(struct nfc_device *pnd, const uint8_t last_cmd_byte) { uint8_t parity; uint8_t counter_hi, counter_lo; uint16_t counter, u16cycles; uint32_t u32cycles; size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } // Read timer BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_hi >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_hi & 0xff); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_lo >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_TCounterVal_lo & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if (pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1) < 0) { return false; } counter_hi = abtRes[off]; counter_lo = abtRes[off + 1]; counter = counter_hi; counter = (counter << 8) + counter_lo; if (counter == 0) { // counter saturated u32cycles = 0xFFFFFFFF; } else { u16cycles = 0xFFFF - counter; u32cycles = u16cycles; u32cycles *= (CHIP_DATA(pnd)->timer_prescaler * 2 + 1); u32cycles++; // Correction depending on PN53x Rx detection handling: // timer stops after 5 (or 2 for PN531) bits are received if (CHIP_DATA(pnd)->type == PN531) { u32cycles -= (2 * 128); } else { u32cycles -= (5 * 128); } // Correction depending on last parity bit sent parity = (last_cmd_byte >> 7) ^ ((last_cmd_byte >> 6) & 1) ^ ((last_cmd_byte >> 5) & 1) ^ ((last_cmd_byte >> 4) & 1) ^ ((last_cmd_byte >> 3) & 1) ^ ((last_cmd_byte >> 2) & 1) ^ ((last_cmd_byte >> 1) & 1) ^ (last_cmd_byte & 1); parity = parity ? 0 : 1; // When sent ...YY (cmd ends with logical 1, so when last parity bit is 1): if (parity) { // it finishes 64us sooner than a ...ZY signal u32cycles += 64; } // Correction depending on device design u32cycles += CHIP_DATA(pnd)->timer_correction; } return u32cycles; } int pn53x_initiator_transceive_bits_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar, uint8_t *pbtRx, uint8_t *pbtRxPar, uint32_t *cycles) { // TODO Do something with these bytes... (void) pbtTxPar; (void) pbtRxPar; uint16_t i; uint8_t sz = 0; int res = 0; size_t szRxBits = 0; // Sorry, no arbitrary parity bits support for now if (!pnd->bPar) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // Sorry, no easy framing support if (pnd->bEasyFraming) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } // TODO CRC support but it probably doesn't make sense for (szTxBits % 8 != 0) ... if (pnd->bCrc) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } __pn53x_init_timer(pnd, *cycles); // Once timer is started, we cannot use Tama commands anymore. // E.g. on SCL3711 timer settings are reset by 0x42 InCommunicateThru command to: // 631a=82 631b=a5 631c=02 631d=00 // Prepare FIFO BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_COMMAND & SYMBOL_COMMAND_TRANSCEIVE); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_FLUSH_BUFFER); for (i = 0; i < ((szTxBits / 8) + 1); i++) { BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, pbtTx[i]); } // Send data BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_START_SEND | ((szTxBits % 8) & SYMBOL_TX_LAST_BITS)); // Let's send the previously constructed WriteRegister command if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } // Recv data // we've to watch for coming data until we decide to timeout. // our PN53x timer saturates after 4.8ms so this function shouldn't be used for // responses coming very late anyway. // Ideally we should implement a real timer here too but looping a few times is good enough. for (i = 0; i < (3 * (CHIP_DATA(pnd)->timer_prescaler * 2 + 1)); i++) { pn53x_read_register(pnd, PN53X_REG_CIU_FIFOLevel, &sz); if (sz > 0) break; } size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } while (1) { BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); for (i = 0; i < sz; i++) { BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); } BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } for (i = 0; i < sz; i++) { pbtRx[i + szRxBits] = abtRes[i + off]; } szRxBits += (size_t)(sz & SYMBOL_FIFO_LEVEL); sz = abtRes[sz + off]; if (sz == 0) break; } szRxBits *= 8; // in bits, not bytes // Recv corrected timer value *cycles = __pn53x_get_timer(pnd, pbtTx[szTxBits / 8]); return szRxBits; } int pn53x_initiator_transceive_bytes_timed(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, uint8_t *pbtRx, const size_t szRx, uint32_t *cycles) { uint16_t i; uint8_t sz = 0; int res = 0; // We can not just send bytes without parity while the PN53X expects we handled them if (!pnd->bPar) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } // Sorry, no easy framing support // TODO to be changed once we'll provide easy framing support from libnfc itself... if (pnd->bEasyFraming) { pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } __pn53x_init_timer(pnd, *cycles); // Once timer is started, we cannot use Tama commands anymore. // E.g. on SCL3711 timer settings are reset by 0x42 InCommunicateThru command to: // 631a=82 631b=a5 631c=02 631d=00 // Prepare FIFO BUFFER_INIT(abtWriteRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtWriteRegisterCmd, WriteRegister); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_Command & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_COMMAND & SYMBOL_COMMAND_TRANSCEIVE); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_FLUSH_BUFFER); for (i = 0; i < szTx; i++) { BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, pbtTx[i]); } // Send data BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming >> 8); BUFFER_APPEND(abtWriteRegisterCmd, PN53X_REG_CIU_BitFraming & 0xff); BUFFER_APPEND(abtWriteRegisterCmd, SYMBOL_START_SEND); // Let's send the previously constructed WriteRegister command if ((res = pn53x_transceive(pnd, abtWriteRegisterCmd, BUFFER_SIZE(abtWriteRegisterCmd), NULL, 0, -1)) < 0) { return res; } // Recv data size_t szRxLen = 0; // we've to watch for coming data until we decide to timeout. // our PN53x timer saturates after 4.8ms so this function shouldn't be used for // responses coming very late anyway. // Ideally we should implement a real timer here too but looping a few times is good enough. for (i = 0; i < (3 * (CHIP_DATA(pnd)->timer_prescaler * 2 + 1)); i++) { pn53x_read_register(pnd, PN53X_REG_CIU_FIFOLevel, &sz); if (sz > 0) break; } size_t off = 0; if (CHIP_DATA(pnd)->type == PN533) { // PN533 prepends its answer by a status byte off = 1; } while (1) { BUFFER_INIT(abtReadRegisterCmd, PN53x_EXTENDED_FRAME__DATA_MAX_LEN); BUFFER_APPEND(abtReadRegisterCmd, ReadRegister); for (i = 0; i < sz; i++) { BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOData & 0xff); } BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel >> 8); BUFFER_APPEND(abtReadRegisterCmd, PN53X_REG_CIU_FIFOLevel & 0xff); uint8_t abtRes[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRes = sizeof(abtRes); // Let's send the previously constructed ReadRegister command if ((res = pn53x_transceive(pnd, abtReadRegisterCmd, BUFFER_SIZE(abtReadRegisterCmd), abtRes, szRes, -1)) < 0) { return res; } if (pbtRx != NULL) { if ((szRxLen + sz) > szRx) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "Buffer size is too short: %" PRIuPTR " available(s), %" PRIuPTR " needed", szRx, szRxLen + sz); return NFC_EOVFLOW; } // Copy the received bytes for (i = 0; i < sz; i++) { pbtRx[i + szRxLen] = abtRes[i + off]; } } szRxLen += (size_t)(sz & SYMBOL_FIFO_LEVEL); sz = abtRes[sz + off]; if (sz == 0) break; } // Recv corrected timer value if (pnd->bCrc) { // We've to compute CRC ourselves to know last byte actually sent uint8_t *pbtTxRaw; pbtTxRaw = (uint8_t *) malloc(szTx + 2); if (!pbtTxRaw) return NFC_ESOFT; memcpy(pbtTxRaw, pbtTx, szTx); iso14443a_crc_append(pbtTxRaw, szTx); *cycles = __pn53x_get_timer(pnd, pbtTxRaw[szTx + 1]); free(pbtTxRaw); } else { *cycles = __pn53x_get_timer(pnd, pbtTx[szTx - 1]); } return szRxLen; } int pn53x_initiator_deselect_target(struct nfc_device *pnd) { pn53x_current_target_free(pnd); return pn53x_InDeselect(pnd, 0); // 0 mean deselect all selected targets } int pn53x_initiator_target_is_present(struct nfc_device *pnd, const nfc_target *pnt) { // Check if the argument target nt is equals to current saved target if (!pn53x_current_target_is(pnd, pnt)) { return NFC_ETGRELEASED; } // Send Card Presence command const uint8_t abtCmd[] = { Diagnose, 0x06 }; uint8_t abtRx[1]; int res = 0; // Card Presence command can take more time than default one: when a card is // removed from the field, the PN53x took few hundred ms more to reply // correctly. (ie. 700 ms should be enough to detect all tested cases) if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, sizeof(abtRx), 700)) < 0) return res; if (res == 1) { return NFC_SUCCESS; } // Target is not reachable anymore pn53x_current_target_free(pnd); return NFC_ETGRELEASED; } #define SAK_ISO14443_4_COMPLIANT 0x20 #define SAK_ISO18092_COMPLIANT 0x40 int pn53x_target_init(struct nfc_device *pnd, nfc_target *pnt, uint8_t *pbtRx, const size_t szRxLen, int timeout) { pn53x_reset_settings(pnd); CHIP_DATA(pnd)->operating_mode = TARGET; pn53x_target_mode ptm = PTM_NORMAL; int res = 0; switch (pnt->nm.nmt) { case NMT_ISO14443A: ptm = PTM_PASSIVE_ONLY; if ((pnt->nti.nai.abtUid[0] != 0x08) || (pnt->nti.nai.szUidLen != 4)) { pnd->last_error = NFC_EINVARG; return pnd->last_error; } pn53x_set_parameters(pnd, PARAM_AUTO_ATR_RES, false); if (CHIP_DATA(pnd)->type == PN532) { // We have a PN532 if ((pnt->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) && (pnd->bAutoIso14443_4)) { // We have a ISO14443-4 tag to emulate and NP_AUTO_14443_4A option is enabled ptm |= PTM_ISO14443_4_PICC_ONLY; // We add ISO14443-4 restriction pn53x_set_parameters(pnd, PARAM_14443_4_PICC, true); } else { pn53x_set_parameters(pnd, PARAM_14443_4_PICC, false); } } break; case NMT_FELICA: ptm = PTM_PASSIVE_ONLY; break; case NMT_DEP: pn53x_set_parameters(pnd, PARAM_AUTO_ATR_RES, true); ptm = PTM_DEP_ONLY; if (pnt->nti.ndi.ndm == NDM_PASSIVE) { ptm |= PTM_PASSIVE_ONLY; // We add passive mode restriction } break; case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_JEWEL: pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; break; } // Let the PN53X be activated by the RF level detector from power down mode if ((res = pn53x_write_register(pnd, PN53X_REG_CIU_TxAuto, SYMBOL_INITIAL_RF_ON, 0x04)) < 0) return res; uint8_t abtMifareParams[6]; uint8_t *pbtMifareParams = NULL; uint8_t *pbtTkt = NULL; size_t szTkt = 0; uint8_t abtFeliCaParams[18]; uint8_t *pbtFeliCaParams = NULL; const uint8_t *pbtNFCID3t = NULL; const uint8_t *pbtGBt = NULL; size_t szGBt = 0; switch (pnt->nm.nmt) { case NMT_ISO14443A: { // Set ATQA (SENS_RES) abtMifareParams[0] = pnt->nti.nai.abtAtqa[1]; abtMifareParams[1] = pnt->nti.nai.abtAtqa[0]; // Set UID // Note: in this mode we can only emulate a single size (4 bytes) UID where the first is hard-wired by PN53x as 0x08 abtMifareParams[2] = pnt->nti.nai.abtUid[1]; abtMifareParams[3] = pnt->nti.nai.abtUid[2]; abtMifareParams[4] = pnt->nti.nai.abtUid[3]; // Set SAK (SEL_RES) abtMifareParams[5] = pnt->nti.nai.btSak; pbtMifareParams = abtMifareParams; // Historical Bytes pbtTkt = iso14443a_locate_historical_bytes(pnt->nti.nai.abtAts, pnt->nti.nai.szAtsLen, &szTkt); } break; case NMT_FELICA: // Set NFCID2t memcpy(abtFeliCaParams, pnt->nti.nfi.abtId, 8); // Set PAD memcpy(abtFeliCaParams + 8, pnt->nti.nfi.abtPad, 8); // Set SystemCode memcpy(abtFeliCaParams + 16, pnt->nti.nfi.abtSysCode, 2); pbtFeliCaParams = abtFeliCaParams; break; case NMT_DEP: // Set NFCID3 pbtNFCID3t = pnt->nti.ndi.abtNFCID3; // Set General Bytes, if relevant szGBt = pnt->nti.ndi.szGB; if (szGBt) pbtGBt = pnt->nti.ndi.abtGB; // Set ISO/IEC 14443 part // Set ATQA (SENS_RES) abtMifareParams[0] = 0x08; abtMifareParams[1] = 0x00; // Set UID // Note: in this mode we can only emulate a single size (4 bytes) UID where the first is hard-wired by PN53x as 0x08 abtMifareParams[2] = 0x12; abtMifareParams[3] = 0x34; abtMifareParams[4] = 0x56; // Set SAK (SEL_RES) abtMifareParams[5] = SAK_ISO18092_COMPLIANT; // Allow ISO/IEC 18092 in DEP mode pbtMifareParams = abtMifareParams; // Set FeliCa part // Set NFCID2t abtFeliCaParams[0] = 0x01; abtFeliCaParams[1] = 0xfe; abtFeliCaParams[2] = 0x12; abtFeliCaParams[3] = 0x34; abtFeliCaParams[4] = 0x56; abtFeliCaParams[5] = 0x78; abtFeliCaParams[6] = 0x90; abtFeliCaParams[7] = 0x12; // Set PAD abtFeliCaParams[8] = 0xc0; abtFeliCaParams[9] = 0xc1; abtFeliCaParams[10] = 0xc2; abtFeliCaParams[11] = 0xc3; abtFeliCaParams[12] = 0xc4; abtFeliCaParams[13] = 0xc5; abtFeliCaParams[14] = 0xc6; abtFeliCaParams[15] = 0xc7; // Set System Code abtFeliCaParams[16] = 0x0f; abtFeliCaParams[17] = 0xab; pbtFeliCaParams = abtFeliCaParams; break; case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_JEWEL: pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; break; } bool targetActivated = false; size_t szRx; while (!targetActivated) { uint8_t btActivatedMode; if ((res = pn53x_TgInitAsTarget(pnd, ptm, pbtMifareParams, pbtTkt, szTkt, pbtFeliCaParams, pbtNFCID3t, pbtGBt, szGBt, pbtRx, szRxLen, &btActivatedMode, timeout)) < 0) { if (res == NFC_ETIMEOUT) { return pn53x_idle(pnd); } return res; } szRx = (size_t) res; nfc_modulation nm = { .nmt = NMT_DEP, // Silent compilation warnings .nbr = NBR_UNDEFINED }; nfc_dep_mode ndm = NDM_UNDEFINED; // Decode activated "mode" switch (btActivatedMode & 0x70) { // Baud rate case 0x00: // 106kbps nm.nbr = NBR_106; break; case 0x10: // 212kbps nm.nbr = NBR_212; break; case 0x20: // 424kbps nm.nbr = NBR_424; break; }; if (btActivatedMode & 0x04) { // D.E.P. nm.nmt = NMT_DEP; if ((btActivatedMode & 0x03) == 0x01) { // Active mode ndm = NDM_ACTIVE; } else { // Passive mode ndm = NDM_PASSIVE; } } else { // Not D.E.P. if ((btActivatedMode & 0x03) == 0x00) { // MIFARE nm.nmt = NMT_ISO14443A; } else if ((btActivatedMode & 0x03) == 0x02) { // FeliCa nm.nmt = NMT_FELICA; } } if (pnt->nm.nmt == nm.nmt) { // Actual activation have the right modulation type if ((pnt->nm.nbr == NBR_UNDEFINED) || (pnt->nm.nbr == nm.nbr)) { // Have the right baud rate (or undefined) if ((pnt->nm.nmt != NMT_DEP) || (pnt->nti.ndi.ndm == NDM_UNDEFINED) || (pnt->nti.ndi.ndm == ndm)) { // Have the right DEP mode (or is not a DEP) targetActivated = true; } } } if (targetActivated) { pnt->nm.nbr = nm.nbr; // Update baud rate if (pnt->nm.nmt == NMT_DEP) { pnt->nti.ndi.ndm = ndm; // Update DEP mode } if (pn53x_current_target_new(pnd, pnt) == NULL) { pnd->last_error = NFC_ESOFT; return pnd->last_error; } if (ptm & PTM_ISO14443_4_PICC_ONLY) { // When PN532 is in PICC target mode, it automatically reply to RATS so // we don't need to forward this command szRx = 0; } } } return szRx; } int pn53x_target_receive_bits(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtRxPar) { size_t szRxBits = 0; uint8_t abtCmd[] = { TgGetInitiatorCommand }; uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; // Try to gather a received frame from the reader if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, -1)) < 0) return res; szRx = (size_t) res; // Get the last bit-count that is stored in the received byte uint8_t ui8rcc; if ((res = pn53x_read_register(pnd, PN53X_REG_CIU_Control, &ui8rcc)) < 0) return res; uint8_t ui8Bits = ui8rcc & SYMBOL_RX_LAST_BITS; // Recover the real frame length in bits size_t szFrameBits = ((szRx - 1 - ((ui8Bits == 0) ? 0 : 1)) * 8) + ui8Bits; // Ignore the status byte from the PN53X here, it was checked earlier in pn53x_transceive() // Check if we should recover the parity bits ourself if (!pnd->bPar) { // Unwrap the response frame if ((res = pn53x_unwrap_frame(abtRx + 1, szFrameBits, pbtRx, pbtRxPar)) < 0) return res; szRxBits = res; } else { // Save the received bits szRxBits = szFrameBits; if ((szRx - 1) > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx - 1); } // Everyting seems ok, return received bits count return szRxBits; } int pn53x_target_receive_bytes(struct nfc_device *pnd, uint8_t *pbtRx, const size_t szRxLen, int timeout) { uint8_t abtCmd[1]; // XXX I think this is not a clean way to provide some kind of "EasyFraming" // but at the moment I have no more better than this if (pnd->bEasyFraming) { switch (CHIP_DATA(pnd)->current_target->nm.nmt) { case NMT_DEP: abtCmd[0] = TgGetData; break; case NMT_ISO14443A: if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) { // We are dealing with a ISO/IEC 14443-4 compliant target if ((CHIP_DATA(pnd)->type == PN532) && (pnd->bAutoIso14443_4)) { // We are using ISO/IEC 14443-4 PICC emulation capability from the PN532 abtCmd[0] = TgGetData; break; } else { // TODO Support EasyFraming for other cases by software pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } } // NO BREAK case NMT_JEWEL: case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_FELICA: abtCmd[0] = TgGetInitiatorCommand; break; } } else { abtCmd[0] = TgGetInitiatorCommand; } // Try to gather a received frame from the reader uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), abtRx, szRx, timeout)) < 0) return pnd->last_error; szRx = (size_t) res; // Save the received bytes count szRx -= 1; if (szRx > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx); // Everyting seems ok, return received bytes count return szRx; } int pn53x_target_send_bits(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTxBits, const uint8_t *pbtTxPar) { size_t szFrameBits = 0; size_t szFrameBytes = 0; uint8_t ui8Bits = 0; uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN] = { TgResponseToInitiator }; int res = 0; // Check if we should prepare the parity bits ourself if (!pnd->bPar) { // Convert data with parity to a frame if ((res = pn53x_wrap_frame(pbtTx, szTxBits, pbtTxPar, abtCmd + 1)) < 0) return res; szFrameBits = res; } else { szFrameBits = szTxBits; } // Retrieve the leading bits ui8Bits = szFrameBits % 8; // Get the amount of frame bytes + optional (1 byte if there are leading bits) szFrameBytes = (szFrameBits / 8) + ((ui8Bits == 0) ? 0 : 1); // When the parity is handled before us, we just copy the data if (pnd->bPar) memcpy(abtCmd + 1, pbtTx, szFrameBytes); // Set the amount of transmission bits in the PN53X chip register if ((res = pn53x_set_tx_bits(pnd, ui8Bits)) < 0) return res; // Try to send the bits to the reader if ((res = pn53x_transceive(pnd, abtCmd, szFrameBytes + 1, NULL, 0, -1)) < 0) return res; // Everyting seems ok, return return sent bits count return szTxBits; } int pn53x_target_send_bytes(struct nfc_device *pnd, const uint8_t *pbtTx, const size_t szTx, int timeout) { uint8_t abtCmd[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; int res = 0; // We can not just send bytes without parity if while the PN53X expects we handled them if (!pnd->bPar) return NFC_ECHIP; // XXX I think this is not a clean way to provide some kind of "EasyFraming" // but at the moment I have no more better than this if (pnd->bEasyFraming) { switch (CHIP_DATA(pnd)->current_target->nm.nmt) { case NMT_DEP: abtCmd[0] = TgSetData; break; case NMT_ISO14443A: if (CHIP_DATA(pnd)->current_target->nti.nai.btSak & SAK_ISO14443_4_COMPLIANT) { // We are dealing with a ISO/IEC 14443-4 compliant target if ((CHIP_DATA(pnd)->type == PN532) && (pnd->bAutoIso14443_4)) { // We are using ISO/IEC 14443-4 PICC emulation capability from the PN532 abtCmd[0] = TgSetData; break; } else { // TODO Support EasyFraming for other cases by software pnd->last_error = NFC_ENOTIMPL; return pnd->last_error; } } // NO BREAK case NMT_JEWEL: case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_FELICA: abtCmd[0] = TgResponseToInitiator; break; } } else { abtCmd[0] = TgResponseToInitiator; } // Copy the data into the command frame memcpy(abtCmd + 1, pbtTx, szTx); // Try to send the bits to the reader if ((res = pn53x_transceive(pnd, abtCmd, szTx + 1, NULL, 0, timeout)) < 0) return res; // Everyting seems ok, return sent byte count return szTx; } static struct sErrorMessage { int iErrorCode; const char *pcErrorMsg; } sErrorMessages[] = { /* Chip-level errors (internal errors, RF errors, etc.) */ { 0x00, "Success" }, { ETIMEOUT, "Timeout" }, // Time Out, the target has not answered { ECRC, "CRC Error" }, // A CRC error has been detected by the CIU { EPARITY, "Parity Error" }, // A Parity error has been detected by the CIU { EBITCOUNT, "Erroneous Bit Count" }, // During an anti-collision/select operation (ISO/IEC14443-3 Type A and ISO/IEC18092 106 kbps passive mode), an erroneous Bit Count has been detected { EFRAMING, "Framing Error" }, // Framing error during MIFARE operation { EBITCOLL, "Bit-collision" }, // An abnormal bit-collision has been detected during bit wise anti-collision at 106 kbps { ESMALLBUF, "Communication Buffer Too Small" }, // Communication buffer size insufficient { EBUFOVF, "Buffer Overflow" }, // RF Buffer overflow has been detected by the CIU (bit BufferOvfl of the register CIU_Error) { ERFPROTO, "RF Protocol Error" }, // RF Protocol error (see PN53x manual) { EOVHEAT, "Chip Overheating" }, // Temperature error: the internal temperature sensor has detected overheating, and therefore has automatically switched off the antenna drivers { EINBUFOVF, "Internal Buffer overflow."}, // Internal buffer overflow { EINVPARAM, "Invalid Parameter"}, // Invalid parameter (range, format, …) { EOPNOTALL, "Operation Not Allowed" }, // Operation not allowed in this configuration (host controller interface) { ECMD, "Command Not Acceptable" }, // Command is not acceptable due to the current context { EOVCURRENT, "Over Current" }, /* DEP errors */ { ERFTIMEOUT, "RF Timeout" }, // In active communication mode, the RF field has not been switched on in time by the counterpart (as defined in NFCIP-1 standard) { EDEPUNKCMD, "Unknown DEP Command" }, { EDEPINVSTATE, "Invalid DEP State" }, // DEP Protocol: Invalid device state, the system is in a state which does not allow the operation { ENAD, "NAD Missing in DEP Frame" }, /* MIFARE */ { EMFAUTH, "Mifare Authentication Error" }, /* Misc */ { EINVRXFRAM, "Invalid Received Frame" }, // DEP Protocol, Mifare or ISO/IEC14443-4: The data format does not match to the specification. { ENSECNOTSUPP, "NFC Secure not supported" }, // Target or Initiator does not support NFC Secure { EBCC, "Wrong UID Check Byte (BCC)" }, // ISO/IEC14443-3: UID Check byte is wrong { ETGREL, "Target Released" }, // Target have been released by initiator { ECID, "Card ID Mismatch" }, // ISO14443 type B: Card ID mismatch, meaning that the expected card has been exchanged with another one. { ECDISCARDED, "Card Discarded" }, // ISO/IEC14443 type B: the card previously activated has disappeared. { ENFCID3, "NFCID3 Mismatch" }, }; const char * pn53x_strerror(const struct nfc_device *pnd) { const char *pcRes = "Unknown error"; size_t i; for (i = 0; i < (sizeof(sErrorMessages) / sizeof(struct sErrorMessage)); i++) { if (sErrorMessages[i].iErrorCode == CHIP_DATA(pnd)->last_status_byte) { pcRes = sErrorMessages[i].pcErrorMsg; break; } } return pcRes; } int pn53x_RFConfiguration__RF_field(struct nfc_device *pnd, bool bEnable) { uint8_t abtCmd[] = { RFConfiguration, RFCI_FIELD, (bEnable) ? 0x01 : 0x00 }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__Various_timings(struct nfc_device *pnd, const uint8_t fATR_RES_Timeout, const uint8_t fRetryTimeout) { uint8_t abtCmd[] = { RFConfiguration, RFCI_TIMING, 0x00, // RFU fATR_RES_Timeout, // ATR_RES timeout (default: 0x0B 102.4 ms) fRetryTimeout // TimeOut during non-DEP communications (default: 0x0A 51.2 ms) }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__MaxRtyCOM(struct nfc_device *pnd, const uint8_t MaxRtyCOM) { uint8_t abtCmd[] = { RFConfiguration, RFCI_RETRY_DATA, MaxRtyCOM // MaxRtyCOM, default: 0x00 (no retry, only one try), inifite: 0xff }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_RFConfiguration__MaxRetries(struct nfc_device *pnd, const uint8_t MxRtyATR, const uint8_t MxRtyPSL, const uint8_t MxRtyPassiveActivation) { // Retry format: 0x00 means only 1 try, 0xff means infinite uint8_t abtCmd[] = { RFConfiguration, RFCI_RETRY_SELECT, MxRtyATR, // MxRtyATR, default: active = 0xff, passive = 0x02 MxRtyPSL, // MxRtyPSL, default: 0x01 MxRtyPassiveActivation // MxRtyPassiveActivation, default: 0xff (0x00 leads to problems with PN531) }; return pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); } int pn53x_SetParameters(struct nfc_device *pnd, const uint8_t ui8Value) { uint8_t abtCmd[] = { SetParameters, ui8Value }; int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 0) { return res; } // We save last parameters in register cache CHIP_DATA(pnd)->ui8Parameters = ui8Value; return NFC_SUCCESS; } int pn532_SAMConfiguration(struct nfc_device *pnd, const pn532_sam_mode sam_mode, int timeout) { uint8_t abtCmd[] = { SAMConfiguration, sam_mode, 0x00, 0x00 }; size_t szCmd = sizeof(abtCmd); if (CHIP_DATA(pnd)->type != PN532) { // This function is not supported by pn531 neither pn533 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } switch (sam_mode) { case PSM_NORMAL: // Normal mode case PSM_WIRED_CARD: // Wired card mode szCmd = 2; break; case PSM_VIRTUAL_CARD: // Virtual card mode case PSM_DUAL_CARD: // Dual card mode // TODO Implement timeout handling szCmd = 3; break; default: pnd->last_error = NFC_EINVARG; return pnd->last_error; } CHIP_DATA(pnd)->sam_mode = sam_mode; return (pn53x_transceive(pnd, abtCmd, szCmd, NULL, 0, timeout)); } int pn53x_PowerDown(struct nfc_device *pnd) { uint8_t abtCmd[] = { PowerDown, 0xf0 }; int res; if ((res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)) < 0) return res; CHIP_DATA(pnd)->power_mode = LOWVBAT; return res; } /** * @brief C wrapper to InListPassiveTarget command * @return Returns selected targets count on success, otherwise returns libnfc's error code (negative value) * * @param pnd struct nfc_device struct pointer that represent currently used device * @param pmInitModulation Desired modulation * @param pbtInitiatorData Optional initiator data used for Felica, ISO14443B, Topaz Polling or for ISO14443A selecting a specific UID * @param szInitiatorData Length of initiator data \a pbtInitiatorData * @param pbtTargetsData pointer on a pre-allocated byte array to receive TargetData[n] as described in pn53x user manual * @param pszTargetsData size_t pointer where size of \a pbtTargetsData will be written * * @note Selected targets count can be found in \a pbtTargetsData[0] if available (i.e. \a pszTargetsData content is more than 0) * @note To decode theses TargetData[n], there is @fn pn53x_decode_target_data */ int pn53x_InListPassiveTarget(struct nfc_device *pnd, const pn53x_modulation pmInitModulation, const uint8_t szMaxTargets, const uint8_t *pbtInitiatorData, const size_t szInitiatorData, uint8_t *pbtTargetsData, size_t *pszTargetsData, int timeout) { uint8_t abtCmd[15] = { InListPassiveTarget }; abtCmd[1] = szMaxTargets; // MaxTg switch (pmInitModulation) { case PM_ISO14443A_106: case PM_FELICA_212: case PM_FELICA_424: // all gone fine. break; case PM_ISO14443B_106: if (!(pnd->btSupportByte & SUPPORT_ISO14443B)) { // Eg. Some PN532 doesn't support type B! pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_JEWEL_106: if (CHIP_DATA(pnd)->type == PN531) { // These modulations are not supported by pn531 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_ISO14443B_212: case PM_ISO14443B_424: case PM_ISO14443B_847: if ((CHIP_DATA(pnd)->type != PN533) || (!(pnd->btSupportByte & SUPPORT_ISO14443B))) { // These modulations are not supported by pn531 neither pn532 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } break; case PM_UNDEFINED: pnd->last_error = NFC_EINVARG; return pnd->last_error; } abtCmd[2] = pmInitModulation; // BrTy, the type of init modulation used for polling a passive tag // Set the optional initiator data (used for Felica, ISO14443B, Topaz Polling or for ISO14443A selecting a specific UID). if (pbtInitiatorData) memcpy(abtCmd + 3, pbtInitiatorData, szInitiatorData); int res = 0; if ((res = pn53x_transceive(pnd, abtCmd, 3 + szInitiatorData, pbtTargetsData, *pszTargetsData, timeout)) < 0) { return res; } *pszTargetsData = (size_t) res; return pbtTargetsData[0]; } int pn53x_InDeselect(struct nfc_device *pnd, const uint8_t ui8Target) { if (CHIP_DATA(pnd)->type == RCS360) { // We should do act here *only* if a target was previously selected uint8_t abtStatus[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szStatus = sizeof(abtStatus); uint8_t abtCmdGetStatus[] = { GetGeneralStatus }; int res = 0; if ((res = pn53x_transceive(pnd, abtCmdGetStatus, sizeof(abtCmdGetStatus), abtStatus, szStatus, -1)) < 0) { return res; } szStatus = (size_t) res; if ((szStatus < 3) || (abtStatus[2] == 0)) { return NFC_SUCCESS; } // No much choice what to deselect actually... uint8_t abtCmdRcs360[] = { InDeselect, 0x01, 0x01 }; return (pn53x_transceive(pnd, abtCmdRcs360, sizeof(abtCmdRcs360), NULL, 0, -1)); } uint8_t abtCmd[] = { InDeselect, ui8Target }; return (pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1)); } int pn53x_InRelease(struct nfc_device *pnd, const uint8_t ui8Target) { int res = 0; if (CHIP_DATA(pnd)->type == RCS360) { // We should do act here *only* if a target was previously selected uint8_t abtStatus[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szStatus = sizeof(abtStatus); uint8_t abtCmdGetStatus[] = { GetGeneralStatus }; if ((res = pn53x_transceive(pnd, abtCmdGetStatus, sizeof(abtCmdGetStatus), abtStatus, szStatus, -1)) < 0) { return res; } szStatus = (size_t) res; if ((szStatus < 3) || (abtStatus[2] == 0)) { return NFC_SUCCESS; } // No much choice what to release actually... uint8_t abtCmdRcs360[] = { InRelease, 0x01, 0x01 }; res = pn53x_transceive(pnd, abtCmdRcs360, sizeof(abtCmdRcs360), NULL, 0, -1); return (res >= 0) ? NFC_SUCCESS : res; } uint8_t abtCmd[] = { InRelease, ui8Target }; res = pn53x_transceive(pnd, abtCmd, sizeof(abtCmd), NULL, 0, -1); return (res >= 0) ? NFC_SUCCESS : res; } int pn53x_InAutoPoll(struct nfc_device *pnd, const pn53x_target_type *ppttTargetTypes, const size_t szTargetTypes, const uint8_t btPollNr, const uint8_t btPeriod, nfc_target *pntTargets, const int timeout) { size_t szTargetFound = 0; if (CHIP_DATA(pnd)->type != PN532) { // This function is not supported by pn531 neither pn533 pnd->last_error = NFC_EDEVNOTSUPP; return pnd->last_error; } // InAutoPoll frame looks like this { 0xd4, 0x60, 0x0f, 0x01, 0x00 } => { direction, command, pollnr, period, types... } size_t szTxInAutoPoll = 3 + szTargetTypes; uint8_t abtCmd[3 + 15] = { InAutoPoll, btPollNr, btPeriod }; for (size_t n = 0; n < szTargetTypes; n++) { abtCmd[3 + n] = ppttTargetTypes[n]; } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = pn53x_transceive(pnd, abtCmd, szTxInAutoPoll, abtRx, szRx, timeout); szRx = (size_t) res; if (res < 0) { return res; } else if (szRx > 0) { szTargetFound = abtRx[0]; if (szTargetFound > 0) { uint8_t ln; uint8_t *pbt = abtRx + 1; /* 1st target */ // Target type pn53x_target_type ptt = *(pbt++); pntTargets[0].nm = pn53x_ptt_to_nm(ptt); // AutoPollTargetData length ln = *(pbt++); if ((res = pn53x_decode_target_data(pbt, ln, CHIP_DATA(pnd)->type, pntTargets[0].nm.nmt, &(pntTargets[0].nti))) < 0) { return res; } pbt += ln; if (abtRx[0] > 1) { /* 2nd target */ // Target type ptt = *(pbt++); pntTargets[1].nm = pn53x_ptt_to_nm(ptt); // AutoPollTargetData length ln = *(pbt++); pn53x_decode_target_data(pbt, ln, CHIP_DATA(pnd)->type, pntTargets[1].nm.nmt, &(pntTargets[1].nti)); } } } return szTargetFound; } /** * @brief Wrapper for InJumpForDEP command * @param pmInitModulation desired initial modulation * @param pbtPassiveInitiatorData NFCID1 (4 bytes) at 106kbps (optionnal, see NFCIP-1: 11.2.1.26) or Polling Request Frame's payload (5 bytes) at 212/424kbps (mandatory, see NFCIP-1: 11.2.2.5) * @param szPassiveInitiatorData size of pbtPassiveInitiatorData content * @param pbtNFCID3i NFCID3 of the initiator * @param pbtGBi General Bytes of the initiator * @param szGBi count of General Bytes * @param[out] pnt \a nfc_target which will be filled by this function */ int pn53x_InJumpForDEP(struct nfc_device *pnd, const nfc_dep_mode ndm, const nfc_baud_rate nbr, const uint8_t *pbtPassiveInitiatorData, const uint8_t *pbtNFCID3i, const uint8_t *pbtGBi, const size_t szGBi, nfc_target *pnt, const int timeout) { // Max frame size = 1 (Command) + 1 (ActPass) + 1 (Baud rate) + 1 (Next) + 5 (PassiveInitiatorData) + 10 (NFCID3) + 48 (General bytes) = 67 bytes uint8_t abtCmd[67] = { InJumpForDEP, (ndm == NDM_ACTIVE) ? 0x01 : 0x00 }; size_t offset = 4; // 1 byte for command, 1 byte for DEP mode (Active/Passive), 1 byte for baud rate, 1 byte for following parameters flag switch (nbr) { case NBR_106: abtCmd[2] = 0x00; // baud rate is 106 kbps break; case NBR_212: abtCmd[2] = 0x01; // baud rate is 212 kbps break; case NBR_424: abtCmd[2] = 0x02; // baud rate is 424 kbps break; case NBR_847: case NBR_UNDEFINED: pnd->last_error = NFC_EINVARG; return pnd->last_error; break; } if (pbtPassiveInitiatorData && (ndm == NDM_PASSIVE)) { /* can't have passive initiator data when using active mode */ switch (nbr) { case NBR_106: abtCmd[3] |= 0x01; memcpy(abtCmd + offset, pbtPassiveInitiatorData, 4); offset += 4; break; case NBR_212: case NBR_424: abtCmd[3] |= 0x01; memcpy(abtCmd + offset, pbtPassiveInitiatorData, 5); offset += 5; break; case NBR_847: case NBR_UNDEFINED: pnd->last_error = NFC_EINVARG; return pnd->last_error; break; } } if (pbtNFCID3i) { abtCmd[3] |= 0x02; memcpy(abtCmd + offset, pbtNFCID3i, 10); offset += 10; } if (szGBi && pbtGBi) { abtCmd[3] |= 0x04; memcpy(abtCmd + offset, pbtGBi, szGBi); offset += szGBi; } uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); int res = 0; // Try to find a target, call the transceive callback function of the current device if ((res = pn53x_transceive(pnd, abtCmd, offset, abtRx, szRx, timeout)) < 0) return res; szRx = (size_t) res; // Make sure one target has been found, the PN53X returns 0x00 if none was available if (abtRx[1] >= 1) { // Is a target struct available if (pnt) { pnt->nm.nmt = NMT_DEP; pnt->nm.nbr = nbr; pnt->nti.ndi.ndm = ndm; memcpy(pnt->nti.ndi.abtNFCID3, abtRx + 2, 10); pnt->nti.ndi.btDID = abtRx[12]; pnt->nti.ndi.btBS = abtRx[13]; pnt->nti.ndi.btBR = abtRx[14]; pnt->nti.ndi.btTO = abtRx[15]; pnt->nti.ndi.btPP = abtRx[16]; if (szRx > 17) { pnt->nti.ndi.szGB = szRx - 17; memcpy(pnt->nti.ndi.abtGB, abtRx + 17, pnt->nti.ndi.szGB); } else { pnt->nti.ndi.szGB = 0; } } } return abtRx[1]; } int pn53x_TgInitAsTarget(struct nfc_device *pnd, pn53x_target_mode ptm, const uint8_t *pbtMifareParams, const uint8_t *pbtTkt, size_t szTkt, const uint8_t *pbtFeliCaParams, const uint8_t *pbtNFCID3t, const uint8_t *pbtGBt, const size_t szGBt, uint8_t *pbtRx, const size_t szRxLen, uint8_t *pbtModeByte, int timeout) { uint8_t abtCmd[39 + 47 + 48] = { TgInitAsTarget }; // Worst case: 39-byte base, 47 bytes max. for General Bytes, 48 bytes max. for Historical Bytes size_t szOptionalBytes = 0; int res = 0; // Clear the target init struct, reset to all zeros memset(abtCmd + 1, 0x00, sizeof(abtCmd) - 1); // Store the target mode in the initialization params abtCmd[1] = ptm; // MIFARE part if (pbtMifareParams) { memcpy(abtCmd + 2, pbtMifareParams, 6); } // FeliCa part if (pbtFeliCaParams) { memcpy(abtCmd + 8, pbtFeliCaParams, 18); } // DEP part if (pbtNFCID3t) { memcpy(abtCmd + 26, pbtNFCID3t, 10); } // General Bytes (ISO/IEC 18092) if ((CHIP_DATA(pnd)->type == PN531) || (CHIP_DATA(pnd)->type == RCS360)) { if (szGBt) { memcpy(abtCmd + 36, pbtGBt, szGBt); szOptionalBytes = szGBt; } } else { abtCmd[36] = (uint8_t)(szGBt); if (szGBt) { memcpy(abtCmd + 37, pbtGBt, szGBt); } szOptionalBytes = szGBt + 1; } // Historical bytes (ISO/IEC 14443-4) if ((CHIP_DATA(pnd)->type != PN531) && (CHIP_DATA(pnd)->type != RCS360)) { // PN531 does not handle Historical Bytes abtCmd[36 + szOptionalBytes] = (uint8_t)(szTkt); if (szTkt) { memcpy(abtCmd + 37 + szOptionalBytes, pbtTkt, szTkt); } szOptionalBytes += szTkt + 1; } // Request the initialization as a target uint8_t abtRx[PN53x_EXTENDED_FRAME__DATA_MAX_LEN]; size_t szRx = sizeof(abtRx); if ((res = pn53x_transceive(pnd, abtCmd, 36 + szOptionalBytes, abtRx, szRx, timeout)) < 0) return res; szRx = (size_t) res; // Note: the first byte is skip: // its the "mode" byte which contains baudrate, DEP and Framing type (Mifare, active or FeliCa) datas. if (pbtModeByte) { *pbtModeByte = abtRx[0]; } // Save the received byte count szRx -= 1; if ((szRx - 1) > szRxLen) return NFC_EOVFLOW; // Copy the received bytes memcpy(pbtRx, abtRx + 1, szRx); return szRx; } int pn53x_check_ack_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen) { if (szRxFrameLen >= sizeof(pn53x_ack_frame)) { if (0 == memcmp(pbtRxFrame, pn53x_ack_frame, sizeof(pn53x_ack_frame))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PN53x ACKed"); return NFC_SUCCESS; } } pnd->last_error = NFC_EIO; log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "%s", "Unexpected PN53x reply!"); return pnd->last_error; } int pn53x_check_error_frame(struct nfc_device *pnd, const uint8_t *pbtRxFrame, const size_t szRxFrameLen) { if (szRxFrameLen >= sizeof(pn53x_error_frame)) { if (0 == memcmp(pbtRxFrame, pn53x_error_frame, sizeof(pn53x_error_frame))) { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_DEBUG, "%s", "PN53x sent an error frame"); pnd->last_error = NFC_EIO; return pnd->last_error; } } return NFC_SUCCESS; } /** * @brief Build a PN53x frame * * @param pbtData payload (bytes array) of the frame, will become PD0, ..., PDn in PN53x frame * @note The first byte of pbtData is the Command Code (CC) */ int pn53x_build_frame(uint8_t *pbtFrame, size_t *pszFrame, const uint8_t *pbtData, const size_t szData) { if (szData <= PN53x_NORMAL_FRAME__DATA_MAX_LEN) { // LEN - Packet length = data length (len) + checksum (1) + end of stream marker (1) pbtFrame[3] = szData + 1; // LCS - Packet length checksum pbtFrame[4] = 256 - (szData + 1); // TFI pbtFrame[5] = 0xD4; // DATA - Copy the PN53X command into the packet buffer memcpy(pbtFrame + 6, pbtData, szData); // DCS - Calculate data payload checksum uint8_t btDCS = (256 - 0xD4); for (size_t szPos = 0; szPos < szData; szPos++) { btDCS -= pbtData[szPos]; } pbtFrame[6 + szData] = btDCS; // 0x00 - End of stream marker pbtFrame[szData + 7] = 0x00; (*pszFrame) = szData + PN53x_NORMAL_FRAME__OVERHEAD; } else if (szData <= PN53x_EXTENDED_FRAME__DATA_MAX_LEN) { // Extended frame marker pbtFrame[3] = 0xff; pbtFrame[4] = 0xff; // LENm pbtFrame[5] = (szData + 1) >> 8; // LENl pbtFrame[6] = (szData + 1) & 0xff; // LCS pbtFrame[7] = 256 - ((pbtFrame[5] + pbtFrame[6]) & 0xff); // TFI pbtFrame[8] = 0xD4; // DATA - Copy the PN53X command into the packet buffer memcpy(pbtFrame + 9, pbtData, szData); // DCS - Calculate data payload checksum uint8_t btDCS = (256 - 0xD4); for (size_t szPos = 0; szPos < szData; szPos++) { btDCS -= pbtData[szPos]; } pbtFrame[9 + szData] = btDCS; // 0x00 - End of stream marker pbtFrame[szData + 10] = 0x00; (*pszFrame) = szData + PN53x_EXTENDED_FRAME__OVERHEAD; } else { log_put(LOG_GROUP, LOG_CATEGORY, NFC_LOG_PRIORITY_ERROR, "We can't send more than %d bytes in a raw (requested: %" PRIdPTR ")", PN53x_EXTENDED_FRAME__DATA_MAX_LEN, szData); return NFC_ECHIP; } return NFC_SUCCESS; } pn53x_modulation pn53x_nm_to_pm(const nfc_modulation nm) { switch (nm.nmt) { case NMT_ISO14443A: return PM_ISO14443A_106; break; case NMT_ISO14443B: switch (nm.nbr) { case NBR_106: return PM_ISO14443B_106; break; case NBR_212: return PM_ISO14443B_212; break; case NBR_424: return PM_ISO14443B_424; break; case NBR_847: return PM_ISO14443B_847; break; case NBR_UNDEFINED: // Nothing to do... break; } break; case NMT_JEWEL: return PM_JEWEL_106; break; case NMT_FELICA: switch (nm.nbr) { case NBR_212: return PM_FELICA_212; break; case NBR_424: return PM_FELICA_424; break; case NBR_106: case NBR_847: case NBR_UNDEFINED: // Nothing to do... break; } break; case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_DEP: // Nothing to do... break; } return PM_UNDEFINED; } nfc_modulation pn53x_ptt_to_nm(const pn53x_target_type ptt) { switch (ptt) { case PTT_GENERIC_PASSIVE_106: case PTT_GENERIC_PASSIVE_212: case PTT_GENERIC_PASSIVE_424: case PTT_UNDEFINED: // XXX This should not happend, how handle it cleanly ? break; case PTT_MIFARE: case PTT_ISO14443_4A_106: return (const nfc_modulation) { .nmt = NMT_ISO14443A, .nbr = NBR_106 }; break; case PTT_ISO14443_4B_106: case PTT_ISO14443_4B_TCL_106: return (const nfc_modulation) { .nmt = NMT_ISO14443B, .nbr = NBR_106 }; break; case PTT_JEWEL_106: return (const nfc_modulation) { .nmt = NMT_JEWEL, .nbr = NBR_106 }; break; case PTT_FELICA_212: return (const nfc_modulation) { .nmt = NMT_FELICA, .nbr = NBR_212 }; break; case PTT_FELICA_424: return (const nfc_modulation) { .nmt = NMT_FELICA, .nbr = NBR_424 }; break; case PTT_DEP_PASSIVE_106: case PTT_DEP_ACTIVE_106: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_106 }; break; case PTT_DEP_PASSIVE_212: case PTT_DEP_ACTIVE_212: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_212 }; break; case PTT_DEP_PASSIVE_424: case PTT_DEP_ACTIVE_424: return (const nfc_modulation) { .nmt = NMT_DEP, .nbr = NBR_424 }; break; } // We should never be here, this line silent compilation warning return (const nfc_modulation) { .nmt = NMT_ISO14443A, .nbr = NBR_106 }; } pn53x_target_type pn53x_nm_to_ptt(const nfc_modulation nm) { switch (nm.nmt) { case NMT_ISO14443A: return PTT_MIFARE; // return PTT_ISO14443_4A_106; break; case NMT_ISO14443B: switch (nm.nbr) { case NBR_106: return PTT_ISO14443_4B_106; break; case NBR_UNDEFINED: case NBR_212: case NBR_424: case NBR_847: // Nothing to do... break; } break; case NMT_JEWEL: return PTT_JEWEL_106; break; case NMT_FELICA: switch (nm.nbr) { case NBR_212: return PTT_FELICA_212; break; case NBR_424: return PTT_FELICA_424; break; case NBR_UNDEFINED: case NBR_106: case NBR_847: // Nothing to do... break; } break; case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: case NMT_DEP: // Nothing to do... break; } return PTT_UNDEFINED; } int pn53x_get_supported_modulation(nfc_device *pnd, const nfc_mode mode, const nfc_modulation_type **const supported_mt) { switch (mode) { case N_TARGET: *supported_mt = CHIP_DATA(pnd)->supported_modulation_as_target; break; case N_INITIATOR: *supported_mt = CHIP_DATA(pnd)->supported_modulation_as_initiator; break; default: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_get_supported_baud_rate(nfc_device *pnd, const nfc_modulation_type nmt, const nfc_baud_rate **const supported_br) { switch (nmt) { case NMT_FELICA: *supported_br = (nfc_baud_rate *)pn53x_felica_supported_baud_rates; break; case NMT_ISO14443A: *supported_br = (nfc_baud_rate *)pn53x_iso14443a_supported_baud_rates; break; case NMT_ISO14443B: case NMT_ISO14443BI: case NMT_ISO14443B2SR: case NMT_ISO14443B2CT: { if ((CHIP_DATA(pnd)->type != PN533)) { *supported_br = (nfc_baud_rate *)pn532_iso14443b_supported_baud_rates; } else { *supported_br = (nfc_baud_rate *)pn533_iso14443b_supported_baud_rates; } } break; case NMT_JEWEL: *supported_br = (nfc_baud_rate *)pn53x_jewel_supported_baud_rates; break; case NMT_DEP: *supported_br = (nfc_baud_rate *)pn53x_dep_supported_baud_rates; break; default: return NFC_EINVARG; } return NFC_SUCCESS; } int pn53x_get_information_about(nfc_device *pnd, char **pbuf) { size_t buflen = 2048; *pbuf = malloc(buflen); if (! *pbuf) { return NFC_ESOFT; } char *buf = *pbuf; int res; if ((res = snprintf(buf, buflen, "chip: %s\n", CHIP_DATA(pnd)->firmware_text)) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = snprintf(buf, buflen, "initator mode modulations: ")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_modulation_type *nmt; if ((res = nfc_device_get_supported_modulation(pnd, N_INITIATOR, &nmt)) < 0) { free(*pbuf); return res; } for (int i = 0; nmt[i]; i++) { if ((res = snprintf(buf, buflen, "%s%s (", (i == 0) ? "" : ", ", str_nfc_modulation_type(nmt[i]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_baud_rate *nbr; if ((res = nfc_device_get_supported_baud_rate(pnd, nmt[i], &nbr)) < 0) { free(*pbuf); return res; } for (int j = 0; nbr[j]; j++) { if ((res = snprintf(buf, buflen, "%s%s", (j == 0) ? "" : ", ", str_nfc_baud_rate(nbr[j]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, ")")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, "\n")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = snprintf(buf, buflen, "target mode modulations: ")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; if ((res = nfc_device_get_supported_modulation(pnd, N_TARGET, &nmt)) < 0) { free(*pbuf); return res; } for (int i = 0; nmt[i]; i++) { if ((res = snprintf(buf, buflen, "%s%s (", (i == 0) ? "" : ", ", str_nfc_modulation_type(nmt[i]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; const nfc_baud_rate *nbr; if ((res = nfc_device_get_supported_baud_rate(pnd, nmt[i], &nbr)) < 0) { free(*pbuf); return res; } for (int j = 0; nbr[j]; j++) { if ((res = snprintf(buf, buflen, "%s%s", (j == 0) ? "" : ", ", str_nfc_baud_rate(nbr[j]))) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, ")")) < 0) { free(*pbuf); return NFC_ESOFT; } buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } buflen -= res; } if ((res = snprintf(buf, buflen, "\n")) < 0) { free(*pbuf); return NFC_ESOFT; } //buf += res; if (buflen <= (size_t)res) { free(*pbuf); return NFC_EOVFLOW; } //buflen -= res; return NFC_SUCCESS; } void * pn53x_current_target_new(const struct nfc_device *pnd, const nfc_target *pnt) { if (pnt == NULL) { return NULL; } // Keep the current nfc_target for further commands if (CHIP_DATA(pnd)->current_target) { free(CHIP_DATA(pnd)->current_target); } CHIP_DATA(pnd)->current_target = malloc(sizeof(nfc_target)); if (!CHIP_DATA(pnd)->current_target) { return NULL; } memcpy(CHIP_DATA(pnd)->current_target, pnt, sizeof(nfc_target)); return CHIP_DATA(pnd)->current_target; } void pn53x_current_target_free(const struct nfc_device *pnd) { if (CHIP_DATA(pnd)->current_target) { free(CHIP_DATA(pnd)->current_target); CHIP_DATA(pnd)->current_target = NULL; } } bool pn53x_current_target_is(const struct nfc_device *pnd, const nfc_target *pnt) { if ((CHIP_DATA(pnd)->current_target == NULL) || (pnt == NULL)) { return false; } // XXX It will not work if t is not binary-equal to current target if (0 != memcmp(pnt, CHIP_DATA(pnd)->current_target, sizeof(nfc_target))) { return false; } return true; } void * pn53x_data_new(struct nfc_device *pnd, const struct pn53x_io *io) { pnd->chip_data = malloc(sizeof(struct pn53x_data)); if (!pnd->chip_data) { return NULL; } // Keep I/O functions CHIP_DATA(pnd)->io = io; // Set type to generic (means unknown) CHIP_DATA(pnd)->type = PN53X; // Set power mode to normal, if your device starts in LowVBat (ie. PN532 // UART) the driver layer have to correctly set it. CHIP_DATA(pnd)->power_mode = NORMAL; // PN53x starts in initiator mode CHIP_DATA(pnd)->operating_mode = INITIATOR; // Clear last status byte CHIP_DATA(pnd)->last_status_byte = 0x00; // Set current target to NULL CHIP_DATA(pnd)->current_target = NULL; // Set current sam_mode to normal mode CHIP_DATA(pnd)->sam_mode = PSM_NORMAL; // WriteBack cache is clean CHIP_DATA(pnd)->wb_trigged = false; memset(CHIP_DATA(pnd)->wb_mask, 0x00, PN53X_CACHE_REGISTER_SIZE); // Set default command timeout (350 ms) CHIP_DATA(pnd)->timeout_command = 350; // Set default ATR timeout (103 ms) CHIP_DATA(pnd)->timeout_atr = 103; // Set default communication timeout (52 ms) CHIP_DATA(pnd)->timeout_communication = 52; CHIP_DATA(pnd)->supported_modulation_as_initiator = NULL; CHIP_DATA(pnd)->supported_modulation_as_target = NULL; return pnd->chip_data; } void pn53x_data_free(struct nfc_device *pnd) { // Free current target pn53x_current_target_free(pnd); // Free supported modulation(s) if (CHIP_DATA(pnd)->supported_modulation_as_initiator) { free(CHIP_DATA(pnd)->supported_modulation_as_initiator); } free(pnd->chip_data); }
zzyjames55-nfc0805
libnfc/chips/pn53x.c
C
lgpl
107,627
# General init # /!\ Don't forget to update 'CMakeLists.txt' too /!\ AC_INIT([libnfc],[1.7.0-rc7],[nfc-tools@googlegroups.com]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADER(config.h) # GIT revison GIT_REVISION=`which git > /dev/null && git describe` if test x"$GIT_REVISION" != x""; then AC_DEFINE_UNQUOTED([GIT_REVISION], ["$GIT_REVISION"], [GIT revision]) fi AM_INIT_AUTOMAKE m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])]) AC_LANG([C]) AC_PROG_CC AC_PROG_MAKE_SET WITH_POSIX_ONLY_EXAMPLES=1 # Libtool LT_INIT case "$host" in *-pc-linux-gnu) AC_MSG_RESULT([Fixing libtool for -rpath problems.]) sed -i -r 's/(hardcode_into_libs)=.*$/\1=no/' libtool ;; *-pc-mingw32msvc) WITH_POSIX_ONLY_EXAMPLES=0 AC_MSG_RESULT([Disable extended examples due to target Windows system.]) # Undefine __STRICT_ANSI__ to allow to use strdup, putenv, etc. without warnings CFLAGS="$CFLAGS -U__STRICT_ANSI__" ;; esac AM_CONDITIONAL(POSIX_ONLY_EXAMPLES_ENABLED, [test "$WITH_POSIX_ONLY_EXAMPLES" = "1"]) PKG_PROG_PKG_CONFIG # Checks for header files. AC_HEADER_STDC AC_HEADER_STDBOOL AC_CHECK_HEADERS([fcntl.h limits.h stdio.h stdlib.h stdint.h stddef.h stdbool.h sys/ioctl.h sys/param.h sys/time.h termios.h]) AC_CHECK_HEADERS([linux/spi/spidev.h], [spi_available="yes"]) AC_CHECK_HEADERS([linux/i2c-dev.h], [i2c_available="yes"]) AC_CHECK_FUNCS([memmove memset select strdup strerror strstr strtol usleep], [AC_DEFINE([_XOPEN_SOURCE], [600], [Enable POSIX extensions if present])]) AC_DEFINE(_NETBSD_SOURCE, 1, [Define on NetBSD to activate all library features]) AC_DEFINE(_DARWIN_C_SOURCE, 1, [Define on Darwin to activate all library features]) # Note: malloc function should be tested but it produces some error while cross-compiling with MinGW # AC_FUNC_MALLOC # Checks for types AC_TYPE_SIZE_T AC_TYPE_UINT8_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_TYPE_INT16_T AC_TYPE_INT32_T AC_TYPE_OFF_T LIBNFC_CFLAGS='-I$(top_srcdir)/libnfc -I$(top_builddir)/include -I$(top_srcdir)/include' AC_SUBST(LIBNFC_CFLAGS) # Log support (default:yes) AC_ARG_ENABLE([log],AS_HELP_STRING([--disable-log],[Disable any logs]),[enable_log=$enableval],[enable_log="yes"]) AC_MSG_CHECKING(for log flag) AC_MSG_RESULT($enable_log) AM_CONDITIONAL([WITH_LOG], [test "$enable_log" != "no"]) if test x"$enable_log" = "xyes" then AC_DEFINE([LOG], [1], [Enable log]) fi # Conffiles support (default:yes) AC_ARG_ENABLE([conffiles],AS_HELP_STRING([--disable-conffiles],[Disable use of config files]),[enable_conffiles=$enableval],[enable_conffiles="yes"]) AC_MSG_CHECKING(for conffiles flag) AC_MSG_RESULT($enable_conffiles) AM_CONDITIONAL([WITH_CONFFILES], [test "$enable_conffiles" != "no"]) if test x"$enable_conffiles" = "xyes" then AC_DEFINE([CONFFILES], [1], [Enable conffiles]) fi # Envvars support (default:yes) AC_ARG_ENABLE([envvars],AS_HELP_STRING([--disable-envvars],[Disable use of environment variables]),[enable_envvars=$enableval],[enable_envvars="yes"]) AC_MSG_CHECKING(for envvars flag) AC_MSG_RESULT($enable_envvars) AM_CONDITIONAL([WITH_ENVVARS], [test "$enable_envvars" != "no"]) if test x"$enable_envvars" = "xyes" then AC_DEFINE([ENVVARS], [1], [Enable envvars]) fi # Debug support (default:no) AC_ARG_ENABLE([debug],AS_HELP_STRING([--enable-debug],[Enable debug mode]),[enable_debug=$enableval],[enable_debug="no"]) AC_MSG_CHECKING(for debug flag) AC_MSG_RESULT($enable_debug) AM_CONDITIONAL([WITH_DEBUG], [test "$enable_debug" != "no"]) if test x"$enable_debug" = "xyes" then AC_DEFINE([DEBUG], [1], [Enable debug flag]) CFLAGS="$CFLAGS -g -O0 -ggdb" fi # Handle --with-drivers option LIBNFC_ARG_WITH_DRIVERS # Enable UART if AM_CONDITIONAL(UART_ENABLED, [test x"$uart_required" = x"yes"]) # Enable SPI if AM_CONDITIONAL(SPI_ENABLED, [test x"$spi_required" = x"yes"]) # Enable I2C if AM_CONDITIONAL(I2C_ENABLED, [test x"$i2c_required" = x"yes"]) # Documentation (default: no) AC_ARG_ENABLE([doc],AS_HELP_STRING([--enable-doc],[Enable documentation generation.]),[enable_doc=$enableval],[enable_doc="no"]) AC_MSG_CHECKING(for documentation request) AC_MSG_RESULT($enable_doc) if test x"$enable_doc" = "xyes" then AC_PATH_PROG([DOXYGEN], [doxygen]) if test x$DOXYGEN = x then AC_MSG_ERROR([doxygen is mandatory.]) fi fi AM_CONDITIONAL(DOC_ENABLED, [test x"$enable_doc" = xyes]) # Dependencies PKG_CONFIG_REQUIRES="" LIBNFC_CHECK_LIBUSB LIBNFC_CHECK_PCSC AC_SUBST(PKG_CONFIG_REQUIRES) AM_CONDITIONAL(LIBUSB_ENABLED, [test "$HAVE_LIBUSB" = "1"]) AM_CONDITIONAL(PCSC_ENABLED, [test "$HAVE_PCSC" = "1"]) CUTTER_REQUIRED_VERSION=1.1.7 m4_ifdef([AC_CHECK_CUTTER], [AC_CHECK_CUTTER([>= $CUTTER_REQUIRED_VERSION])], [ac_cv_use_cutter="no"]) if test x$ac_cv_with_cutter = xyes -a x$ac_cv_use_cutter = xno; then AC_MSG_ERROR([cutter >= $CUTTER_REQUIRED_VERSION is mandatory.]) fi AM_CONDITIONAL([WITH_CUTTER], [test "$ac_cv_use_cutter" != "no"]) AC_CHECK_READLINE # Help us to write great code ;-) CFLAGS="$CFLAGS -Wall -pedantic -Wextra" # Defines and C flags CFLAGS="$CFLAGS -std=c99" # Workarounds for libusb in c99 CFLAGS="$CFLAGS -Du_int8_t=uint8_t -Du_int16_t=uint16_t" AC_CONFIG_FILES([ Doxyfile Makefile cmake/Makefile cmake/modules/Makefile contrib/Makefile contrib/devd/Makefile contrib/libnfc/Makefile contrib/linux/Makefile contrib/udev/Makefile contrib/win32/Makefile contrib/win32/sys/Makefile contrib/win32/libnfc/Makefile contrib/win32/libnfc/buses/Makefile examples/Makefile examples/pn53x-tamashell-scripts/Makefile include/Makefile include/nfc/Makefile libnfc.pc libnfc/Makefile libnfc/buses/Makefile libnfc/chips/Makefile libnfc/drivers/Makefile test/Makefile utils/Makefile ]) AC_OUTPUT LIBNFC_DRIVERS_SUMMARY
zzyjames55-nfc0805
configure.ac
M4Sugar
lgpl
5,816
SET(LIBNFC_DRIVER_ACR122_PCSC OFF CACHE BOOL "Enable ACR122 support (Depends on PC/SC)") SET(LIBNFC_DRIVER_ACR122_USB ON CACHE BOOL "Enable ACR122 support (Direct USB connection)") SET(LIBNFC_DRIVER_ACR122S ON CACHE BOOL "Enable ACR122S support (Use serial port)") SET(LIBNFC_DRIVER_ARYGON ON CACHE BOOL "Enable ARYGON support (Use serial port)") IF(WIN32) SET(LIBNFC_DRIVER_PN532_I2C OFF CACHE BOOL "Enable PN532 I2C support (Use I2C bus)") SET(LIBNFC_DRIVER_PN532_SPI OFF CACHE BOOL "Enable PN532 SPI support (Use SPI bus)") ELSE(WIN32) SET(LIBNFC_DRIVER_PN532_I2C ON CACHE BOOL "Enable PN532 I2C support (Use I2C bus)") SET(LIBNFC_DRIVER_PN532_SPI ON CACHE BOOL "Enable PN532 SPI support (Use SPI bus)") ENDIF(WIN32) SET(LIBNFC_DRIVER_PN532_UART ON CACHE BOOL "Enable PN532 UART support (Use serial port)") SET(LIBNFC_DRIVER_PN53X_USB ON CACHE BOOL "Enable PN531 and PN531 USB support (Depends on libusb)") IF(LIBNFC_DRIVER_ACR122_PCSC) FIND_PACKAGE(PCSC REQUIRED) ADD_DEFINITIONS("-DDRIVER_ACR122_PCSC_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/acr122_pcsc") ENDIF(LIBNFC_DRIVER_ACR122_PCSC) IF(LIBNFC_DRIVER_ACR122_USB) FIND_PACKAGE(LIBUSB REQUIRED) ADD_DEFINITIONS("-DDRIVER_ACR122_USB_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/acr122_usb") ENDIF(LIBNFC_DRIVER_ACR122_USB) IF(LIBNFC_DRIVER_ACR122S) ADD_DEFINITIONS("-DDRIVER_ACR122S_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/acr122s") SET(UART_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_ACR122S) IF(LIBNFC_DRIVER_ARYGON) ADD_DEFINITIONS("-DDRIVER_ARYGON_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/arygon") SET(UART_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_ARYGON) IF(LIBNFC_DRIVER_PN532_I2C) ADD_DEFINITIONS("-DDRIVER_PN532_I2C_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/pn532_i2c") SET(I2C_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_PN532_I2C) IF(LIBNFC_DRIVER_PN532_SPI) ADD_DEFINITIONS("-DDRIVER_PN532_SPI_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/pn532_spi") SET(SPI_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_PN532_SPI) IF(LIBNFC_DRIVER_PN532_UART) ADD_DEFINITIONS("-DDRIVER_PN532_UART_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/pn532_uart") SET(UART_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_PN532_UART) IF(LIBNFC_DRIVER_PN53X_USB) FIND_PACKAGE(LIBUSB REQUIRED) ADD_DEFINITIONS("-DDRIVER_PN53X_USB_ENABLED") SET(DRIVERS_SOURCES ${DRIVERS_SOURCES} "drivers/pn53x_usb") SET(USB_REQUIRED TRUE) ENDIF(LIBNFC_DRIVER_PN53X_USB) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/drivers)
zzyjames55-nfc0805
cmake/modules/LibnfcDrivers.cmake
CMake
lgpl
2,579
# - Run Doxygen # # Adds a doxygen target that runs doxygen to generate the html # and optionally the LaTeX API documentation. # The doxygen target is added to the doc target as dependency. # i.e.: the API documentation is built with: # make doc # # USAGE: GLOBAL INSTALL # # Install it with: # cmake ./ && sudo make install # Add the following to the CMakeLists.txt of your project: # include(UseDoxygen OPTIONAL) # Optionally copy Doxyfile.in in the directory of CMakeLists.txt and edit it. # # USAGE: INCLUDE IN PROJECT # # set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}) # include(UseDoxygen) # Add the Doxyfile.in and UseDoxygen.cmake files to the projects source directory. # # # Variables you may define are: # DOXYFILE_OUTPUT_DIR - Path where the Doxygen output is stored. Defaults to "doc". # # DOXYFILE_LATEX_DIR - Directory where the Doxygen LaTeX output is stored. Defaults to "latex". # # DOXYFILE_HTML_DIR - Directory where the Doxygen html output is stored. Defaults to "html". # # # Copyright (c) 2009 Tobias Rautenkranz <tobias@rautenkranz.ch> # # Redistribution and use is allowed according to the terms of the New # BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # macro(usedoxygen_set_default name value) if(NOT DEFINED "${name}") set("${name}" "${value}") endif() endmacro() find_package(Doxygen) if(DOXYGEN_FOUND) find_file(DOXYFILE_IN "Doxyfile.in" PATHS "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_ROOT}/Modules/") include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Doxyfile.in DEFAULT_MSG DOXYFILE_IN) endif() if(DOXYGEN_FOUND AND DOXYFILE_IN) add_custom_target(doxygen ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile) usedoxygen_set_default(DOXYFILE_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/doc") usedoxygen_set_default(DOXYFILE_HTML_DIR "html") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_HTML_DIR}") set(DOXYFILE_LATEX "NO") set(DOXYFILE_PDFLATEX "NO") set(DOXYFILE_DOT "NO") find_package(LATEX) if(LATEX_COMPILER AND MAKEINDEX_COMPILER) set(DOXYFILE_LATEX "YES") usedoxygen_set_default(DOXYFILE_LATEX_DIR "latex") set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_LATEX_DIR}") if(PDFLATEX_COMPILER) set(DOXYFILE_PDFLATEX "YES") endif() if(DOXYGEN_DOT_EXECUTABLE) set(DOXYFILE_DOT "YES") endif() add_custom_command(TARGET doxygen POST_BUILD COMMAND ${CMAKE_MAKE_PROGRAM} WORKING_DIRECTORY "${DOXYFILE_OUTPUT_DIR}/${DOXYFILE_LATEX_DIR}") endif() configure_file(${DOXYFILE_IN} Doxyfile ESCAPE_QUOTES IMMEDIATE @ONLY) get_target_property(DOC_TARGET doc TYPE) if(NOT DOC_TARGET) add_custom_target(doc) endif() add_dependencies(doc doxygen) endif()
zzyjames55-nfc0805
cmake/modules/UseDoxygen.cmake
CMake
lgpl
2,841
EXTRA_DIST = \ COPYING-CMAKE-SCRIPTS \ FindLIBUSB.cmake \ FindPCSC.cmake \ FindPCRE.cmake \ UseDoxygen.cmake \ LibnfcDrivers.cmake
zzyjames55-nfc0805
cmake/modules/Makefile.am
Makefile
lgpl
137
# This CMake script wants to use pcre functionality needed for windows # compilation. However, since PCRE isn't really a default install location # there isn't much to search. # # Operating Systems Supported: # - Windows (requires MinGW) # Tested with Windows XP/Windows 7 # # This should work for both 32 bit and 64 bit systems. # # Author: A. Lian <alex.lian@gmail.com> # IF(WIN32) IF(NOT PCRE_FOUND) FIND_PATH(PCRE_INCLUDE_DIRS regex.h) FIND_LIBRARY(PCRE_LIBRARIES NAMES PCRE pcre) IF(PCRE_INCLUDE_DIRS AND PCRE_LIBRARIES) SET(PCRE_FOUND TRUE) ENDIF(PCRE_INCLUDE_DIRS AND PCRE_LIBRARIES) ENDIF(NOT PCRE_FOUND) IF(PCRE_FOUND) IF(NOT PCRE_FIND_QUIETLY) MESSAGE(STATUS "Found PCRE: ${PCRE_LIBRARIES} ${PCRE_INCLUDE_DIRS}") ENDIF (NOT PCRE_FIND_QUIETLY) ELSE(PCRE_FOUND) IF(PCRE_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find PCRE") ENDIF(PCRE_FIND_REQUIRED) ENDIF(PCRE_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(PCRE DEFAULT_MSG PCRE_LIBRARIES PCRE_INCLUDE_DIRS ) ENDIF(WIN32)
zzyjames55-nfc0805
cmake/modules/FindPCRE.cmake
CMake
lgpl
1,101
# This CMake script wants to use libusb functionality, therefore it looks # for libusb include files and libraries. # # Operating Systems Supported: # - Unix (requires pkg-config) # Tested with Ubuntu 9.04 and Fedora 11 # - Windows (requires MinGW) # Tested with Windows XP/Windows 7 # # This should work for both 32 bit and 64 bit systems. # # Author: F. Kooman <fkooman@tuxed.net> # # FreeBSD has built-in libusb since 800069 IF(CMAKE_SYSTEM_NAME MATCHES FreeBSD) EXEC_PROGRAM(sysctl ARGS -n kern.osreldate OUTPUT_VARIABLE FREEBSD_VERSION) SET(MIN_FREEBSD_VERSION 800068) IF(FREEBSD_VERSION GREATER ${MIN_FREEBSD_VERSION}) SET(LIBUSB_FOUND TRUE) SET(LIBUSB_INCLUDE_DIRS "/usr/include") SET(LIBUSB_LIBRARIES "usb") SET(LIBUSB_LIBRARY_DIRS "/usr/lib/") ENDIF(FREEBSD_VERSION GREATER ${MIN_FREEBSD_VERSION}) ENDIF(CMAKE_SYSTEM_NAME MATCHES FreeBSD) IF(NOT LIBUSB_FOUND) IF(WIN32) FIND_PATH(LIBUSB_INCLUDE_DIRS lusb0_usb.h "$ENV{ProgramFiles}/LibUSB-Win32/include" NO_SYSTEM_ENVIRONMENT_PATH) FIND_LIBRARY(LIBUSB_LIBRARIES NAMES libusb PATHS "$ENV{ProgramFiles}/LibUSB-Win32/lib/gcc") SET(LIBUSB_LIBRARY_DIR "$ENV{ProgramFiles}/LibUSB-Win32/bin/x86/") # Must fix up variable to avoid backslashes during packaging STRING(REGEX REPLACE "\\\\" "/" LIBUSB_LIBRARY_DIR ${LIBUSB_LIBRARY_DIR}) ELSE(WIN32) # If not under Windows we use PkgConfig FIND_PACKAGE (PkgConfig) IF(PKG_CONFIG_FOUND) PKG_CHECK_MODULES(LIBUSB REQUIRED libusb) ELSE(PKG_CONFIG_FOUND) MESSAGE(FATAL_ERROR "Could not find PkgConfig") ENDIF(PKG_CONFIG_FOUND) ENDIF(WIN32) IF(LIBUSB_INCLUDE_DIRS AND LIBUSB_LIBRARIES) SET(LIBUSB_FOUND TRUE) ENDIF(LIBUSB_INCLUDE_DIRS AND LIBUSB_LIBRARIES) ENDIF(NOT LIBUSB_FOUND) IF(LIBUSB_FOUND) IF(NOT LIBUSB_FIND_QUIETLY) MESSAGE(STATUS "Found LIBUSB: ${LIBUSB_LIBRARIES} ${LIBUSB_INCLUDE_DIRS}") ENDIF (NOT LIBUSB_FIND_QUIETLY) ELSE(LIBUSB_FOUND) IF(LIBUSB_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find LIBUSB") ENDIF(LIBUSB_FIND_REQUIRED) ENDIF(LIBUSB_FOUND)
zzyjames55-nfc0805
cmake/modules/FindLIBUSB.cmake
CMake
lgpl
2,081
# - Try to find the PC/SC smart card library # Once done this will define # # PCSC_FOUND - system has the PC/SC library # PCSC_INCLUDE_DIRS - the PC/SC include directory # PCSC_LIBRARIES - The libraries needed to use PC/SC # # Author: F. Kooman <fkooman@tuxed.net> # Version: 20101019 # FIND_PACKAGE (PkgConfig) IF(PKG_CONFIG_FOUND) # Will find PC/SC library on Linux/BSDs using PkgConfig PKG_CHECK_MODULES(PCSC libpcsclite) # PKG_CHECK_MODULES(PCSC QUIET libpcsclite) # IF CMake >= 2.8.2? ENDIF(PKG_CONFIG_FOUND) IF(NOT PCSC_FOUND) # Will find PC/SC headers both on Mac and Windows FIND_PATH(PCSC_INCLUDE_DIRS WinSCard.h) # PCSC library is for Mac, WinSCard library is for Windows FIND_LIBRARY(PCSC_LIBRARIES NAMES PCSC libwinscard) ENDIF(NOT PCSC_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(PCSC DEFAULT_MSG PCSC_LIBRARIES PCSC_INCLUDE_DIRS ) MARK_AS_ADVANCED(PCSC_INCLUDE_DIRS PCSC_LIBRARIES)
zzyjames55-nfc0805
cmake/modules/FindPCSC.cmake
CMake
lgpl
967
INCLUDE(BundleUtilities) # set bundle to the full path of the executable already existing in the install tree SET(bundle "${CMAKE_INSTALL_PREFIX}/bin/nfc-list@CMAKE_EXECUTABLE_SUFFIX@") # set other_libs to a list of additional libs that cannot be reached by dependency analysis SET(other_libs "") SET(dirs "@LIBUSB_LIBRARY_DIR@") fixup_bundle("${bundle}" "${other_libs}" "${dirs}")
zzyjames55-nfc0805
cmake/FixBundle.cmake.in
CMake
lgpl
386
#include "contrib/windows.h" #cmakedefine PACKAGE_NAME "@PACKAGE_NAME@" #cmakedefine PACKAGE_VERSION "@PACKAGE_VERSION@" #cmakedefine PACKAGE_STRING "@PACKAGE_STRING@" #cmakedefine LIBNFC_SYSCONFDIR "@LIBNFC_SYSCONFDIR@"
zzyjames55-nfc0805
cmake/config_windows.h.cmake
CMake
lgpl
222
SUBDIRS = modules EXTRA_DIST = \ FixBundle.cmake.in \ config_posix.h.cmake \ config_windows.h.cmake
zzyjames55-nfc0805
cmake/Makefile.am
Makefile
lgpl
119
#cmakedefine PACKAGE_NAME "@PACKAGE_NAME@" #cmakedefine PACKAGE_VERSION "@PACKAGE_VERSION@" #cmakedefine PACKAGE_STRING "@PACKAGE_STRING@" #cmakedefine _XOPEN_SOURCE @_XOPEN_SOURCE@ #cmakedefine SYSCONFDIR "@SYSCONFDIR@"
zzyjames55-nfc0805
cmake/config_posix.h.cmake
CMake
lgpl
221
PROJECT(libnfc C) CMAKE_MINIMUM_REQUIRED(VERSION 2.6) SET(VERSION_MAJOR "1") SET(VERSION_MINOR "7") SET(VERSION_PATCH "0") SET(VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}") SET(PACKAGE_NAME "libnfc") SET(PACKAGE_VERSION ${VERSION}) SET(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") # config.h IF(WIN32) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake/config_windows.h.cmake ${CMAKE_CURRENT_SOURCE_DIR}/config.h) SET(LIBNFC_SYSCONFDIR "${CMAKE_INSTALL_PREFIX}/config" CACHE PATH "libnfc configuration directory") INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/contrib/win32) ELSE(WIN32) SET(_XOPEN_SOURCE 600) SET(SYSCONFDIR "/etc" CACHE PATH "System configuration directory") CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/cmake/config_posix.h.cmake ${CMAKE_CURRENT_SOURCE_DIR}/config.h) ENDIF(WIN32) ADD_DEFINITIONS("-DHAVE_CONFIG_H") INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/include) # make it easy to locate CMake modules for finding libraries SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules/") # Options SET(LIBNFC_LOG ON CACHE BOOL "Enable log facility (errors, warning, info and debug messages)") IF(LIBNFC_LOG) ADD_DEFINITIONS(-DLOG) ENDIF(LIBNFC_LOG) SET(LIBNFC_ENVVARS ON CACHE BOOL "Enable envvars facility") IF(LIBNFC_ENVVARS) ADD_DEFINITIONS(-DENVVARS) ENDIF(LIBNFC_ENVVARS) SET(LIBNFC_DEBUG_MODE OFF CACHE BOOL "Debug mode") IF(LIBNFC_DEBUG_MODE) ADD_DEFINITIONS(-DDEBUG) SET(CMAKE_C_FLAGS "-g3 ${CMAKE_C_FLAGS}") SET(WIN32_MODE "debug") SET(CMAKE_RC_FLAGS "-D_DEBUG ${CMAKE_RC_FLAGS}") ELSE(LIBNFC_DEBUG_MODE) SET(WIN32_MODE "release") ENDIF(LIBNFC_DEBUG_MODE) # Doxygen SET(builddir "${CMAKE_BINARY_DIR}") SET(top_srcdir "${CMAKE_SOURCE_DIR}") INCLUDE(UseDoxygen) IF(DEFINED CMAKE_INSTALL_LIBDIR) SET(libdir ${CMAKE_INSTALL_LIBDIR}) ELSE(DEFINED CMAKE_INSTALL_LIBDIR) SET(CMAKE_INSTALL_LIBDIR lib) SET(libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}) ENDIF(DEFINED CMAKE_INSTALL_LIBDIR) IF(DEFINED INCLUDE_INSTALL_DIR) SET(includedir ${INCLUDE_INSTALL_DIR}) ELSE(DEFINED INCLUDE_INSTALL_DIR) SET(INCLUDE_INSTALL_DIR include) SET(includedir ${CMAKE_INSTALL_PREFIX}/${INCLUDE_INSTALL_DIR}) ENDIF(DEFINED INCLUDE_INSTALL_DIR) IF(NOT DEFINED SHARE_INSTALL_PREFIX) SET(SHARE_INSTALL_PREFIX share) ENDIF(NOT DEFINED SHARE_INSTALL_PREFIX) # Additonnal GCC flags IF(CMAKE_COMPILER_IS_GNUCC) # Make sure we will not miss some warnings ;) SET(CMAKE_C_FLAGS "-Wall -pedantic -std=c99 ${CMAKE_C_FLAGS}") ENDIF(CMAKE_COMPILER_IS_GNUCC) # Workarounds for libusb in C99 ADD_DEFINITIONS(-Du_int8_t=uint8_t -Du_int16_t=uint16_t) IF(MINGW) # force MinGW-w64 in 32bit mode SET(CMAKE_C_FLAGS "-m32 ${CMAKE_C_FLAGS}") SET(CMAKE_MODULE_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_SHARED_LINKER_FLAGS}") SET(CMAKE_SHARED_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_SHARED_LINKER_FLAGS}") SET(CMAKE_EXE_LINKER_FLAGS "-m32 -Wl,--enable-stdcall-fixup ${CMAKE_EXE_LINKER_FLAGS}") SET(CMAKE_RC_FLAGS "--target=pe-i386 --output-format=coff ${CMAKE_RC_FLAGS}") ENDIF(MINGW) IF(NOT WIN32) # Set some pkg-config variables SET(prefix ${CMAKE_INSTALL_PREFIX}) SET(exec_prefix ${CMAKE_INSTALL_PREFIX}) SET(PACKAGE "libnfc") IF(LIBNFC_DRIVER_PN53X_USB) SET(PKG_REQ ${PKG_REQ} "libusb") ENDIF(LIBNFC_DRIVER_PN53X_USB) IF(LIBNFC_DRIVER_ACR122) SET(PKG_REQ ${PKG_REQ} "libpcsclite") ENDIF(LIBNFC_DRIVER_ACR122) # CMake lists are separated by a semi colon, replace with colon STRING(REPLACE ";" "," PKG_CONFIG_REQUIRES "${PKG_REQ}") CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/libnfc.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libnfc.pc @ONLY) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/libnfc.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) ENDIF(NOT WIN32) # Require PCRE for Win32 IF (WIN32) FIND_PACKAGE(PCRE REQUIRED) IF(PCRE_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${PCRE_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCRE_LIBRARY_DIRS}) ENDIF(PCRE_INCLUDE_DIRS) ENDIF(WIN32) INCLUDE(LibnfcDrivers) IF(PCSC_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${PCSC_INCLUDE_DIRS}) LINK_DIRECTORIES(${PCSC_LIBRARY_DIRS}) ENDIF(PCSC_INCLUDE_DIRS) IF(LIBUSB_INCLUDE_DIRS) INCLUDE_DIRECTORIES(${LIBUSB_INCLUDE_DIRS}) LINK_DIRECTORIES(${LIBUSB_LIBRARY_DIRS}) SET(LIBUSB_FOUND TRUE) ENDIF(LIBUSB_INCLUDE_DIRS) # version.rc for Windows IF(WIN32) # Date for filling in rc file information MACRO (GET_CURRENT_YEAR RESULT) EXECUTE_PROCESS(COMMAND "cmd" " /C date /T" OUTPUT_VARIABLE ${RESULT}) STRING(REGEX REPLACE ".*(..)/(..)/(....).*" "\\3" ${RESULT} ${${RESULT}}) ENDMACRO (GET_CURRENT_YEAR) GET_CURRENT_YEAR(CURRENT_YEAR) MESSAGE("Year for copyright is " ${CURRENT_YEAR}) SET(RC_COMMENT "${PACKAGE_NAME} library") SET(RC_INTERNAL_NAME "${PACKAGE_NAME} ${WIN32_MODE}") SET(RC_ORIGINAL_NAME ${PACKAGE_NAME}.dll) SET(RC_FILE_TYPE VFT_DLL) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/contrib/win32/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/windows/libnfc.rc @ONLY) ENDIF(WIN32) ADD_SUBDIRECTORY(libnfc) ADD_SUBDIRECTORY(include) ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(examples) # Binary Package IF(WIN32) SET(CPACK_GENERATOR "ZIP") ELSE(WIN32) SET(CPACK_GENERATOR "TBZ2") ENDIF(WIN32) SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Near Field Communication (NFC) library") SET(CPACK_PACKAGE_VENDOR "Roel Verdult") SET(CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/README") SET(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") SET(CPACK_PACKAGE_INSTALL_DIRECTORY "libnfc") SET(CPACK_PACKAGE_VERSION_MAJOR ${VERSION_MAJOR}) SET(CPACK_PACKAGE_VERSION_MINOR ${VERSION_MINOR}) SET(CPACK_PACKAGE_VERSION_PATCH ${VERSION_PATCH}) SET(CPACK_COMPONENT_LIBRARIES_DISPLAY_NAME "NFC Library") SET(CPACK_COMPONENT_EXAMPLES_DISPLAY_NAME "Example Applications") SET(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "Development Headers") IF(NOT WIN32) SET(CPACK_COMPONENT_MANUALS_DISPLAY_NAME "Example Applications Manuals") SET(CPACK_COMPONENT_MANUALS_DISABLED TRUE) SET(CPACK_COMPONENT_MANUALS_DEPENDS examples) ENDIF(NOT WIN32) SET(CPACK_COMPONENT_HEADERS_DISABLED TRUE) SET(CPACK_COMPONENT_HEADERS_DEPENDS libraries) SET(CPACK_COMPONENT_EXAMPLES_DEPENDS libraries) # Source Package IF(WIN32) SET(CPACK_SOURCE_GENERATOR "ZIP") ELSE(WIN32) SET(CPACK_SOURCE_GENERATOR "ZIP;TBZ2") ENDIF(WIN32) SET(CPACK_SOURCE_PACKAGE_FILE_NAME "libnfc-${VERSION}") SET(CPACK_SOURCE_IGNORE_FILES "~$" "/\\\\.git/" "bin/") INCLUDE(CPack)
zzyjames55-nfc0805
CMakeLists.txt
CMake
lgpl
6,520
#include <cutter.h> #include <nfc/nfc.h> #define NTESTS 10 #define MAX_DEVICE_COUNT 8 #define MAX_TARGET_COUNT 8 /* * This is basically a stress-test to ensure we don't left a device in an * inconsistent state after use. */ void test_access_storm(void); void test_access_storm(void) { int n = NTESTS; nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t ref_device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!ref_device_count) cut_omit("No NFC device found"); while (n) { size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); cut_assert_equal_int(ref_device_count, device_count, cut_message("device count")); for (volatile size_t i = 0; i < device_count; i++) { nfc_device *device; nfc_target ant[MAX_TARGET_COUNT]; device = nfc_open(context, connstrings[i]); cut_assert_not_null(device, cut_message("nfc_open")); res = nfc_initiator_init(device); cut_assert_equal_int(0, res, cut_message("nfc_initiator_init")); const nfc_modulation nm = { .nmt = NMT_ISO14443A, .nbr = NBR_106, }; res = nfc_initiator_list_passive_targets(device, nm, ant, MAX_TARGET_COUNT); cut_assert_operator_int(res, >= , 0, cut_message("nfc_initiator_list_passive_targets")); nfc_close(device); } n--; } nfc_exit(context); }
zzyjames55-nfc0805
test/test_access_storm.c
C
lgpl
1,447
#include <cutter.h> #include <nfc/nfc.h> #define MAX_DEVICE_COUNT 1 #define MAX_TARGET_COUNT 1 void test_register_endianness(void); #include "chips/pn53x.h" void test_register_endianness(void) { nfc_connstring connstrings[MAX_DEVICE_COUNT]; int res = 0; nfc_context *context; nfc_init(&context); size_t device_count = nfc_list_devices(context, connstrings, MAX_DEVICE_COUNT); if (!device_count) cut_omit("No NFC device found"); nfc_device *device; device = nfc_open(context, connstrings[0]); cut_assert_not_null(device, cut_message("nfc_open")); uint8_t value; /* Read valid XRAM memory */ res = pn53x_read_register(device, 0xF0FF, &value); cut_assert_equal_int(0, res, cut_message("read register 0xF0FF")); /* Read invalid SFR register */ res = pn53x_read_register(device, 0xFFF0, &value); cut_assert_equal_int(-1, res, cut_message("read register 0xFFF0")); nfc_close(device); nfc_exit(context); }
zzyjames55-nfc0805
test/test_register_endianness.c
C
lgpl
952