Skip to content

Instantly share code, notes, and snippets.

@huggre
Last active December 15, 2018 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huggre/a52a93006d0598619a2c013d8a265d71 to your computer and use it in GitHub Desktop.
Save huggre/a52a93006d0598619a2c013d8a265d71 to your computer and use it in GitHub Desktop.
# Import the PyOTA library
import iota
from iota import Address
from iota import Transaction
from iota import TryteString
from iota.crypto.kerl import Kerl
# Import datetime libary
import datetime
# Import from PrettyTable
from prettytable import PrettyTable
# Import requests
import requests
# Import json
import json
# Set UPC URL and KEY
upcURL = "https://api.upcdatabase.org/product"
upcKEY = "BC5BD15B042DF904FE3ACC7FE3EBDE3C"
# Define full node to be used when uploading/downloading inventory records from the tangle
NodeURL = "https://nodes.thetangle.org:443"
# Create IOTA object
api=iota.Iota(NodeURL)
# Function for generating addresses based on a UPC item ID
def CreateAddress(upc_ID):
upc_tryte = TryteString.from_unicode(upc_ID)
astrits = TryteString(str(upc_tryte).encode()).as_trits()
checksum_trits = []
sponge = Kerl()
sponge.absorb(astrits)
sponge.squeeze(checksum_trits)
result = TryteString.from_trits(checksum_trits)
new_address = Address(result)
return(new_address.with_valid_checksum())
# Function for adding/removing items from stock
def UpdateStock(stock_change):
# Get barcode ID
upc_ID = input("Scan barcode..:")
# Get stock change quantity
qty = input("Specify quantity: ")
# Create upload json
udata = {'Stock Change' : stock_change, 'Quantity' : qty}
mystring = json.dumps(udata)
# Create address based on UPC code
addr = CreateAddress(upc_ID)
# Define new IOTA transaction
pt = iota.ProposedTransaction(address = iota.Address(addr), message = iota.TryteString.from_unicode(mystring), tag = iota.Tag(b'HOTELIOTA'), value=0)
# Print waiting message
print("\nSending transaction...Please wait...")
# Send transaction to the tangle
FinalBundle = api.send_transfer(depth=3, transfers=[pt], min_weight_magnitude=14)['bundle']
# Print confirmation message
print("\nTransaction completed.")
print("\nIOTA address used for the transaction was:")
print(addr)
def StockReport():
# Get barcode from scanner..
upc_ID = input("Scan barcode..:")
# Get IOTA address where item records is stored
addr = CreateAddress(upc_ID)
Address = []
Address.append(addr)
# Create PrettyTable object
x = PrettyTable()
# Specify column headers for the table
x.field_names = ["Stock Change", "Quantity", "Date/Time"]
# Find all transacions for selected IOTA address
result = api.find_transactions(addresses=Address)
# Create a list of transaction hashes
myhashes = result['hashes']
# Print wait message
print("\nPlease wait while retrieving inventory records from the tangle...")
# Get item data from UPC database
upc_lookup = upcURL + "/" + upc_ID + "/" + upcKEY
upc_data = requests.get(upc_lookup).json()
# Print UPC item data to the terminal
if upc_data['status'] == 200:
print("\nUPC item title: " + upc_data['title'])
print("UPC item description: " + upc_data['description'])
else:
print("\nItem was not found in UPC database")
# Define items in stock counter
in_stock = 0
# Loop trough all transaction hashes
for txn_hash in myhashes:
# Convert to bytes
txn_hash_as_bytes = bytes(txn_hash)
# Get the raw transaction data (trytes) of transaction
gt_result = api.get_trytes([txn_hash_as_bytes])
# Convert to string
trytes = str(gt_result['trytes'][0])
# Get transaction object
txn = Transaction.from_tryte_string(trytes)
# Get transaction timestamp
timestamp = txn.timestamp
# Convert timestamp to datetime
change_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
# Get transaction message as string
txn_data = str(txn.signature_message_fragment.decode())
# Convert to json
json_data = json.loads(txn_data)
# Check if json data has the expected json tag's
if all(key in json.dumps(json_data) for key in ["Stock Change","Quantity"]):
# Add table row with json values
x.add_row([json_data['Stock Change'], json_data['Quantity'], change_time])
# Get transaction item quantity and appenf/subtract from total quantity
if json_data['Stock Change'] == "+":
in_stock = in_stock + int(json_data['Quantity'])
elif json_data['Stock Change'] == "-":
in_stock = in_stock - int(json_data['Quantity'])
# Sort table by datetime
x.sortby = "Date/Time"
# Print table to terminal
print(x)
# Print item quantity currently in stock
print("Items currently in stock: " + str(in_stock))
# Show main menu
ans=True
while ans:
print ("""
1. Add to stock
2. Remove from stock
3. Stock report
4. Exit
""")
# Get menu selection
itemID = input("Select from menu:")
if itemID=="1":
UpdateStock("+")
elif itemID=="2":
UpdateStock("-")
elif itemID=="3":
StockReport()
elif itemID=="4":
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment