How to use getstring method in tox

Best Python code snippet using tox_python

CLI_Wallet.py

Source:CLI_Wallet.py Github

copy

Full Screen

1#!/usr/bin/env python32##########################################3# Duino-Coin CLI Wallet (v2.7.1)4# https://github.com/revoxhere/duino-coin5# Distributed under MIT license6# © Duino-Coin Community 20227##########################################8import configparser9import datetime10import getpass11import json12import os13from os import _exit, execl, mkdir14from os import path15import platform16import socket17import sys18import time19from pathlib import Path20from signal import SIGINT, signal21from base64 import b64decode, b64encode22from platform import system as plsystem23from locale import LC_ALL, getdefaultlocale, getlocale, setlocale24from json import load as jsonload25try:26 import requests27except:28 now = datetime.datetime.now()29 print(now.strftime("%H:%M:%S ") +30 "Requests is not installed. "31 + "Please install it using: python3 -m pip install requests."32 + "\nExiting in 15s.")33 time.sleep(15)34 os._exit(1)35wrong_passphrase = False36iterations = 100_00037timeout = 30 # Socket timeout38VER = 2.7139RESOURCES_DIR = 'CLI_Wallet_' + str(VER) + '_resources'40use_wrapper = False41WS_URI = "ws://server.duinocoin.com:15808"42config = configparser.ConfigParser()43# Check if the resources folder exists, and makes one if not44if not path.exists(RESOURCES_DIR):45 mkdir(RESOURCES_DIR)46# Check if commands file exists47if not Path(RESOURCES_DIR + "/cli_wallet_commands.json").is_file():48 url = ("https://raw.githubusercontent.com/"49 + "revoxhere/"50 + "duino-coin/master/Resources/"51 + "cli_wallet_commands.json")52 r = requests.get(url)53 with open(RESOURCES_DIR + "/cli_wallet_commands.json", "wb") as f:54 f.write(r.content)55# Check if languages file exists56if not Path(RESOURCES_DIR + "/langs.json").is_file():57 url = ("https://raw.githubusercontent.com/"58 + "revoxhere/"59 + "duino-coin/master/Resources/"60 + "CLI_Wallet_langs.json")61 r = requests.get(url)62 with open(RESOURCES_DIR + "/langs.json", "wb") as f:63 f.write(r.content)64# Load language file65with open(RESOURCES_DIR + "/langs.json", "r", encoding="utf8") as lang_file:66 lang_file = jsonload(lang_file)67# OS X invalid locale hack68if plsystem() == "Darwin":69 if getlocale()[0] is None:70 setlocale(LC_ALL, "en_US.UTF-8")71# Check if wallet is configured, if it isn't, autodetect language72try:73 if not Path(RESOURCES_DIR + "/CLIWallet_config.cfg").is_file():74 locale = getdefaultlocale()[0]75 if locale.startswith("nl"):76 lang = "dutch"77 elif locale.startswith("th"):78 lang = "thai"79 elif locale.startswith("sk"):80 lang = "slovak"81 elif locale.startswith("ko"):82 lang = "korean"83 else:84 lang = "english"85 else:86 # Read language variable from configfile87 try:88 config.read(RESOURCES_DIR + "/CLIWallet_config.cfg")89 lang = config["wallet"]["language"]90 except Exception:91 # If it fails, fallback to english92 lang = "english"93except Exception as error:94 lang = "english"95def getString(string_name):96 # Get string form language file97 if string_name in lang_file[lang]:98 return lang_file[lang][string_name]99 elif string_name in lang_file["english"]:100 return lang_file["english"][string_name]101 else:102 return "String not found: " + string_name103try:104 from base64 import urlsafe_b64decode as b64d105 from base64 import urlsafe_b64encode as b64e106except ModuleNotFoundError:107 print(getString("base64_not_installed"))108 time.sleep(15)109 _exit(1)110try:111 from cryptography.fernet import Fernet, InvalidToken112 from cryptography.hazmat.backends import default_backend113 from cryptography.hazmat.primitives import hashes114 from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC115except:116 now = datetime.datetime.now()117 print(now.strftime("%H:%M:%S ") + getString("cryptography_not_installed"))118 time.sleep(15)119 os._exit(1)120try:121 import secrets122except:123 now = datetime.datetime.now()124 print(now.strftime("%H:%M:%S ") + getString("secrets_not_installed"))125 time.sleep(15)126 os._exit(1)127try:128 import websocket129except:130 now = datetime.datetime.now()131 print(now.strftime("%H:%M:%S ") + getString("websocket_not_installed"))132 time.sleep(15)133 os._exit(1)134try: # Check if colorama is installed135 from colorama import Back, Fore, Style, init136except:137 now = datetime.datetime.now()138 print(now.strftime("%H:%M:%S ") + getString("colorama_not_installed"))139 time.sleep(15)140 os._exit(1)141try:142 import tronpy143 from tronpy.keys import PrivateKey144 tronpy_installed = True145except:146 tronpy_installed = False147 now = datetime.datetime.now()148 print(now.strftime("%H:%M:%S ") + getString("tronpy_not_installed"))149backend = default_backend()150def title(title):151 if os.name == 'nt':152 os.system(153 "title "154 + title)155 else:156 print(157 '\33]0;'158 + title159 + '\a',160 end='')161 sys.stdout.flush()162def _derive_key(163 password: bytes,164 salt: bytes,165 iterations: int = iterations) -> bytes:166 kdf = PBKDF2HMAC(167 algorithm=hashes.SHA256(),168 length=32,169 salt=salt,170 iterations=iterations,171 backend=backend)172 return b64e(kdf.derive(password))173def print_command(name, desc):174 print(" " + Style.RESET_ALL + Fore.WHITE +175 Style.BRIGHT + name + Style.RESET_ALL + desc)176# Print the command names and description using a json file177def print_commands_norm():178 with open(RESOURCES_DIR + '/cli_wallet_commands.json') as f:179 data = json.load(f)180 for key, value in data.items():181 if key == "wrapper_commands":182 break183 print_command(key, value)184def print_commands_wrapper():185 with open(RESOURCES_DIR + '/cli_wallet_commands.json') as f:186 data = json.load(f)187 for key in data["wrapper_commands"]:188 print_command(key, data["wrapper_commands"][key])189def password_encrypt(190 message: bytes,191 password: str,192 iterations: int = iterations) -> bytes:193 salt = secrets.token_bytes(16)194 key = _derive_key(195 password.encode(),196 salt,197 iterations)198 return b64e(199 b'%b%b%b' % (200 salt,201 iterations.to_bytes(4, 'big'),202 b64d(Fernet(key).encrypt(message))))203def password_decrypt(204 token: bytes,205 password: str) -> bytes:206 decoded = b64d(token)207 salt, iterations, token = decoded[:16], decoded[16:20], b64e(decoded[20:])208 iterations = int.from_bytes(iterations, 'big')209 key = _derive_key(210 password.encode(),211 salt,212 iterations)213 return Fernet(key).decrypt(token)214def handler(signal_received, frame):215 print(Style.RESET_ALL216 + Style.BRIGHT217 + Fore.YELLOW218 + getString("see_you_soon"))219 try:220 wss_conn.send(bytes("CLOSE", encoding="utf8"))221 except:222 pass223 os._exit(0)224signal(SIGINT, handler) # Enable signal handler225while True:226 print(("Warning: CLI and GUI wallets are being deprecated "227 + "in favor of the Web Wallet. "228 + "This app may not run properly."))229 try:230 wss_conn = websocket.create_connection(WS_URI)231 SERVER_VER = wss_conn.recv().decode()232 jsonapi = requests.get(233 "https://raw.githubusercontent.com/"234 + "revoxhere/"235 + "duco-statistics/master/api.json",236 data=None)237 if jsonapi.status_code == 200:238 content = jsonapi.content.decode()239 contentjson = json.loads(content)240 ducofiat = float(contentjson["Duco price"])241 else:242 ducofiat = 0.0025243 break244 except Exception as e:245 print(e)246 print(Style.RESET_ALL247 + Fore.RED248 + getString("cant_connect_to_server"))249 time.sleep(15)250 os._exit(1)251 except:252 print(Style.RESET_ALL253 + Fore.RED254 + getString("cant_recieve_pool_ip_and_port"))255 time.sleep(15)256 os._exit(1)257def reconnect():258 while True:259 try:260 # Try to connect261 wss_conn = websocket.create_connection(WS_URI)262 wss_conn.settimeout(timeout)263 SERVER_VER = wss_conn.recv().decode().rstrip("\n")264 jsonapi = requests.get(265 "https://raw.githubusercontent.com/"266 + "revoxhere/"267 + "duco-statistics/master/api.json",268 data=None)269 if jsonapi.status_code == 200:270 content = jsonapi.content.decode()271 contentjson = json.loads(content)272 ducofiat = float(contentjson["Duco price"])273 else:274 ducofiat = 0.0025275 except:276 print(Style.RESET_ALL + Fore.RED277 + getString("cant_connect_to_server"))278 time.sleep(15)279 os.system("python " + __file__)280 else:281 return wss_conn282while True:283 title("Duino-Coin CLI Wallet")284 if not Path(RESOURCES_DIR + "/CLIWallet_config.cfg").is_file():285 # Initial configuration section286 print(Style.RESET_ALL287 + Style.BRIGHT288 + Fore.YELLOW289 + getString("first_run"))290 print(Style.RESET_ALL + getString("select_option"))291 choice = input(getString("choice_input"))292 try:293 int(choice)294 except ValueError:295 print(getString("value_not_numeric"))296 if int(choice) <= 1:297 username = input(298 Style.RESET_ALL299 + Fore.YELLOW300 + getString("enter_username")301 + Style.BRIGHT)302 password = getpass.getpass(prompt=Style.RESET_ALL303 + Fore.YELLOW304 + getString("enter_password")305 + Style.BRIGHT,306 stream=None)307 server_timeout = True308 while server_timeout:309 try:310 wss_conn.send(bytes(311 "LOGI,"312 + str(username)313 + ","314 + str(password)315 + str(",placeholder"),316 encoding="utf8"))317 loginFeedback = wss_conn.recv().decode()318 loginFeedback = loginFeedback.rstrip("\n").split(",")319 server_timeout = False320 if loginFeedback[0] == "OK":321 print(Style.RESET_ALL322 + Fore.YELLOW323 + getString("login_success"))324 config['wallet'] = {325 "username": username,326 "password": b64encode(327 bytes(password, encoding="utf8")328 ).decode("utf-8"),329 "language": lang}330 config['wrapper'] = {"use_wrapper": "false"}331 # Write data to file332 with open(RESOURCES_DIR333 + "/CLIWallet_config.cfg",334 "w") as configfile:335 config.write(configfile)336 else:337 print(Style.RESET_ALL338 + Fore.RED339 + getString("login_failed")340 + Style.BRIGHT341 + str(loginFeedback[1]))342 time.sleep(15)343 os._exit(1)344 except socket.timeout:345 server_timeout = True346 if int(choice) == 2:347 print(Style.RESET_ALL348 + Fore.YELLOW349 + getString("agree_requirments")350 + Fore.WHITE351 + "https://github.com/revoxhere/duino-coin#terms-of-usage"352 + Fore.YELLOW)353 username = input(354 Style.RESET_ALL355 + Fore.YELLOW356 + getString("enter_username")357 + Style.BRIGHT)358 password = getpass.getpass(prompt=Style.RESET_ALL359 + Fore.YELLOW360 + getString("enter_password")361 + Style.BRIGHT,362 stream=None)363 pconfirm = getpass.getpass(prompt=Style.RESET_ALL364 + Fore.YELLOW365 + getString("confirm_password")366 + Style.BRIGHT,367 stream=None)368 email = input(369 Style.RESET_ALL370 + Fore.YELLOW371 + getString("enter_email")372 + Style.BRIGHT)373 if password == pconfirm:374 while True:375 wss_conn.send(bytes(376 "REGI,"377 + str(username)378 + ","379 + str(password)380 + ","381 + str(email),382 encoding="utf8"))383 regiFeedback = wss_conn.recv().decode()384 regiFeedback = regiFeedback.rstrip("\n").split(",")385 if regiFeedback[0] == "OK":386 print(Style.RESET_ALL387 + Fore.YELLOW388 + Style.BRIGHT389 + getString("register_success"))390 break391 elif regiFeedback[0] == "NO":392 print(Style.RESET_ALL393 + Fore.RED394 + getString("register_failed")395 + Style.BRIGHT396 + str(regiFeedback[1]))397 time.sleep(15)398 os._exit(1)399 if int(choice) >= 3:400 os._exit(0)401 else:402 config.read(RESOURCES_DIR + "/CLIWallet_config.cfg")403 if config["wrapper"]["use_wrapper"] == "true" and tronpy_installed:404 use_wrapper = True405 if config["wrapper"]["use_custom_passphrase"] == "true":406 passphrase = getpass.getpass(407 prompt=Style.RESET_ALL408 + Fore.YELLOW409 + getString("decrypt_private_key")410 + Style.BRIGHT,411 stream=None)412 try:413 priv_key = password_decrypt(414 config["wrapper"]["priv_key"],415 passphrase).decode("utf8")416 except InvalidToken:417 print(getString("invalid_passphrase_wrapper"))418 use_wrapper = False419 wrong_passphrase = True420 else:421 try:422 priv_key = password_decrypt(423 config["wrapper"]["priv_key"],424 b64decode(425 config["wallet"]["password"]426 ).decode("utf8")427 ).decode("utf8")428 except InvalidToken:429 print(getString("invalid_passphrase_wrapper"))430 use_wrapper = False431 wrong_passphrase = True432 pub_key = config["wrapper"]["pub_key"]433 while True:434 try:435 tron = tronpy.Tron()436 # wDUCO contract437 wduco = tron.get_contract(438 "TWYaXdxA12JywrUdou3PFD1fvx2PWjqK9U"439 )440 break441 except:442 print("Retrying wDUCO contract fetch")443 pass444 while True:445 try:446 wbalance = wduco.functions.balanceOf(447 config["wrapper"]["pub_key"])448 break449 except:450 print("Retrying wDUCO balance fetch")451 try:452 trx_balance = tron.get_account_balance(453 config["wrapper"]["pub_key"]454 )455 except:456 trx_balance = 0457 while True:458 config.read(RESOURCES_DIR + "/CLIWallet_config.cfg")459 username = config["wallet"]["username"]460 password = b64decode(config["wallet"]["password"]).decode("utf8")461 print("Authenticating...")462 wss_conn.send(bytes(463 "LOGI,"464 + str(username)465 + ","466 + str(password)467 + str(",placeholder"),468 encoding="utf8"))469 loginFeedback = wss_conn.recv().decode().rstrip("\n").split(",")470 if loginFeedback[0] == "OK":471 break472 else:473 print(Style.RESET_ALL474 + Fore.RED475 + getString("login_failed")476 + Style.BRIGHT477 + str(loginFeedback[1]))478 time.sleep(15)479 os._exit(1)480 while True:481 while True:482 try:483 wss_conn.send(bytes(484 "BALA",485 encoding="utf8"))486 except:487 wss_conn = reconnect()488 try:489 balance = round(490 float(wss_conn.recv().decode().rstrip("\n")), 8)491 balanceusd = round(492 float(balance) * float(ducofiat), 6)493 break494 except:495 pass496 if use_wrapper:497 while True:498 try:499 wbalance = float(500 wduco.functions.balanceOf(pub_key)501 )/10**6502 break503 except:504 pass505 try:506 trx_balance = tron.get_account_balance(pub_key)507 except:508 trx_balance = 0509 print(Style.RESET_ALL510 + Style.BRIGHT511 + Fore.YELLOW512 + getString("cli_wallet_text"))513 print(Style.RESET_ALL514 + Fore.YELLOW515 + getString("you_have")516 + Style.BRIGHT517 + str(balance)518 + " DUCO")519 print(Style.RESET_ALL520 + Fore.YELLOW521 + getString("which_is_about")522 + Style.BRIGHT523 + str(balanceusd)524 + " USD")525 print(Style.RESET_ALL526 + Fore.YELLOW527 + getString("duco_price")528 + Style.BRIGHT529 + str(ducofiat)530 + " USD")531 if use_wrapper:532 print(Style.RESET_ALL533 + Fore.YELLOW534 + getString("you_have")535 + Style.BRIGHT536 + str(wbalance)537 + " wDUCO")538 while True:539 try:540 pendingbalance = float(541 wduco.functions.pendingWithdrawals(542 pub_key,543 username)544 )/(10**6)545 break546 except:547 pass548 if pendingbalance > 0:549 print(Style.RESET_ALL550 + Fore.YELLOW551 + getString("pending_unwraps")552 + Style.BRIGHT553 + str(pendingbalance)554 + " wDUCO")555 print(Style.RESET_ALL556 + Fore.YELLOW557 + getString("tron_address")558 + Style.BRIGHT559 + str(pub_key))560 print(Style.RESET_ALL561 + Fore.YELLOW562 + getString("trx_balance")563 + Style.BRIGHT564 + str(trx_balance))565 print(Style.RESET_ALL566 + Fore.YELLOW567 + getString("help_list_command"))568 command = input(Style.RESET_ALL569 + Fore.WHITE570 + getString("duco_console")571 + Style.BRIGHT)572 if command == "refresh":573 continue574 elif command == "clear":575 if os.name == "nt":576 os.system("cls")577 continue578 else:579 os.system("clear")580 continue581 elif command == "send":582 recipient = input(Style.RESET_ALL583 + Fore.WHITE584 + getString("enter_recipients_name")585 + Style.BRIGHT)586 try:587 amount = float(input(588 Style.RESET_ALL589 + Fore.WHITE590 + getString("enter_amount_transfer")591 + Style.BRIGHT))592 except ValueError:593 print(getString("amount_numeric"))594 continue595 wss_conn.send(bytes(596 "SEND,-,"597 + str(recipient)598 + ","599 + str(amount),600 encoding="utf8"))601 while True:602 message = wss_conn.recv().decode().rstrip("\n")603 print(Style.RESET_ALL604 + Fore.BLUE605 + getString("server_message")606 + Style.BRIGHT607 + str(message))608 break609 elif command == "changepass":610 oldpassword = input(611 Style.RESET_ALL612 + Fore.WHITE613 + getString("enter_current_password")614 + Style.BRIGHT)615 newpassword = input(616 Style.RESET_ALL617 + Fore.WHITE618 + getString("enter_new_password")619 + Style.BRIGHT)620 wss_conn.send(bytes(621 "CHGP,"622 + str(oldpassword)623 + ","624 + str(newpassword),625 encoding="utf8"))626 while True:627 message = wss_conn.recv().decode().rstrip("\n")628 print(Style.RESET_ALL629 + Fore.BLUE630 + getString("server_message")631 + Style.BRIGHT632 + str(message))633 break634 elif command == "exit":635 print(Style.RESET_ALL636 + Style.BRIGHT637 + Fore.YELLOW638 + getString("sigint_detected")639 + Style.NORMAL640 + getString("see_you_soon")641 + Style.RESET_ALL)642 try:643 wss_conn.send(bytes("CLOSE", encoding="utf8"))644 except:645 pass646 os._exit(0)647 elif command == "wrapperconf": # wrapper config648 config.read(RESOURCES_DIR + "/CLIWallet_config.cfg")649 if (not config["wrapper"]["use_wrapper"] == "true"650 and tronpy_installed):651 print(Style.RESET_ALL652 + Fore.WHITE653 + getString("select_option"))654 try:655 choice = int(656 input(getString("choice_input_wrapper")))657 if choice <= 1:658 priv_key = str(PrivateKey.random())659 pub_key = PrivateKey(bytes.fromhex(660 priv_key)).public_key.to_base58check_address()661 print(getString("how_encrypt_private_key"))662 incorrect_value = True663 while incorrect_value:664 try:665 encryption_choice = int(666 input(getString("encryption_choice")))667 incorrect_value = False668 except ValueError:669 print(getString("value_not_numeric"))670 incorrect_value = True671 if encryption_choice <= 1:672 config['wrapper'] = {673 "use_wrapper": "true",674 "priv_key": str(password_encrypt(675 priv_key.encode(),676 password).decode()),677 "pub_key": pub_key,678 "use_custom_passphrase": "false"}679 # Write data to file680 with open(RESOURCES_DIR681 + "/CLIWallet_config.cfg",682 "w") as configfile:683 config.write(configfile)684 print(getString("success"))685 elif encryption_choice >= 2:686 passphrase = input(687 getString("encrypt_private_key"))688 config['wrapper'] = {689 "use_wrapper": "true",690 "priv_key": str(password_encrypt(691 priv_key.encode(),692 passphrase).decode()),693 "pub_key": pub_key,694 "use_custom_passphrase": "true"}695 # Write data to file696 with open(RESOURCES_DIR697 + "/CLIWallet_config.cfg",698 "w") as configfile:699 config.write(configfile)700 print(getString("success"))701 print("Restart the wallet to use the wrapper")702 elif choice == 2:703 priv_key = input(getString("input_private_key"))704 try:705 pub_key = PrivateKey(706 bytes.fromhex(707 priv_key)708 ).public_key.to_base58check_address()709 print(getString("how_encrypt_private_key"))710 incorrect_value = True711 while incorrect_value:712 try:713 encryption_choice = int(714 input(715 getString("encryption_choice")716 )717 )718 incorrect_value = False719 except ValueError:720 print(getString("value_not_numeric"))721 incorrect_value = True722 if encryption_choice <= 1:723 config['wrapper'] = {724 "use_wrapper": "true",725 "priv_key": str(password_encrypt(726 priv_key.encode(),727 password).decode()),728 "pub_key": pub_key,729 "use_custom_passphrase": "false"}730 # Write data to file731 with open(RESOURCES_DIR732 + "/CLIWallet_config.cfg",733 "w") as configfile:734 config.write(configfile)735 print(getString("success"))736 elif encryption_choice >= 2:737 passphrase = input(738 getString("encrypt_private_key"))739 config['wrapper'] = {740 "use_wrapper": "true",741 "priv_key": str(password_encrypt(742 priv_key.encode(),743 passphrase).decode()),744 "pub_key": pub_key,745 "use_custom_passphrase": "true"}746 # Write data to file747 with open(RESOURCES_DIR748 + "/CLIWallet_config.cfg",749 "w") as configfile:750 config.write(configfile)751 print(getString("success"))752 except ValueError:753 print(getString("incorrect_key"))754 else:755 print(getString("cancelled"))756 except ValueError:757 print(Style.RESET_ALL758 + Fore.WHITE759 + getString("incorrect_value")760 + Style.BRIGHT)761 elif not tronpy_installed:762 print(now.strftime(763 "%H:%M:%S ")764 + getString("tronpy_not_installed_2"))765 elif command == "wrap":766 if use_wrapper:767 try:768 amount = float(input(769 Style.RESET_ALL770 + Fore.WHITE771 + getString("amount_to_wrap")772 + Style.BRIGHT))773 except ValueError:774 print(getString("no_amount_numeric"))775 continue776 try:777 wss_conn.send(bytes("BALA", encoding="utf8"))778 balance = round(779 float(wss_conn.recv().decode().rstrip("\n")), 8)780 except:781 wss_conn = reconnect()782 if float(amount) >= 10 and float(amount) <= balance:783 tron_address = input(784 Style.RESET_ALL785 + Fore.WHITE786 + getString("enter_tron_address_or_local")787 + Style.BRIGHT)788 if tron_address == "":789 tron_address = pub_key790 wss_conn.send(bytes(791 "WRAP,"792 + str(amount)793 + ","794 + str(tron_address)795 + str(",placeholder"),796 encoding='utf8'))797 elif float(amount) < 10 and not float(amount) > balance:798 print(getString("error_min_10_duco"))799 else:800 print(getString("error_unsufficient_balance"))801 elif wrong_passphrase:802 print(getString("error_wrong_passphrase"))803 else:804 print(getString("error_configure_wrapperconf"))805 elif command == "unwrap":806 if use_wrapper:807 pendingvalues = wduco.functions.pendingWithdrawals(808 pub_key, username809 )810 # Transaction wasn't initiated811 # but variable should be declared812 txn_success = False813 try:814 amount = float(815 input(Style.RESET_ALL816 + Fore.WHITE817 + getString("enter_amount_unwrap")818 + Style.BRIGHT))819 except ValueError:820 print(getString("value_not_numeric"))821 continue822 if int(float(amount)*10**6) >= pendingvalues:823 toInit = int(float(amount)*10**6)-pendingvalues824 else:825 toInit = amount*10**6826 if toInit > 0:827 txn = wduco.functions.initiateWithdraw(828 username, toInit829 ).with_owner(830 pub_key831 ).fee_limit(832 5_000_000833 ).build().sign(834 PrivateKey(835 bytes.fromhex(priv_key)836 )837 )838 print(getString("initiating_unwrap"), txn.txid)839 txn = txn.broadcast()840 txnfeedback = txn.result()841 if txnfeedback:842 txn_success = True843 else:844 txn_success = False845 if amount <= pendingvalues:846 print(getString("amount_over_pending_values"))847 if txn_success or amount <= pendingvalues:848 wss_conn.send(bytes(849 "UNWRAP,"850 + str(amount)851 + ","852 + str(pub_key),853 encoding='utf8'))854 else:855 print(getString("error_initiating_unwrap"))856 elif wrong_passphrase:857 print(getString("error_wrong_passphrase"))858 else:859 print(getString("error_configure_wrapperconf"))860 elif command == "cancelunwraps":861 if use_wrapper:862 txn = wduco.functions.cancelWithdrawals(863 pub_key, username864 ).with_owner(865 pub_key866 ).fee_limit(867 5_000_000868 ).build().sign(869 PrivateKey(870 bytes.fromhex(priv_key)871 )872 )873 print(getString("transaction_send_txid"), txn.txid)874 txn = txn.broadcast()875 if txn.result():876 print(getString("success"))877 else:878 print(getString("error_not_enough_energy_or_trx"))879 elif wrong_passphrase:880 print(getString("error_wrong_passphrase"))881 else:882 print(getString("error_configure_wrapperconf"))883 elif command == "finishunwraps":884 if use_wrapper:885 pendingvalues = float(886 wduco.functions.pendingWithdrawals(887 pub_key,888 username))/(10**6)889 wss_conn.send(bytes(890 "UNWRAP,"891 + str(pendingvalues)892 + ","893 + str(pub_key)894 + str(",placeholder"),895 encoding='utf8'))896 print(getString("finished_unwrapping"),897 str(pendingvalues), "DUCO")898 elif wrong_passphrase:899 print(getString("error_wrong_passphrase"))900 else:901 print(getString("error_configure_wrapperconf"))902 elif command == "exportwrapkey":903 if use_wrapper:904 confirmation = input(905 getString("confirm_export_private_key"))906 if confirmation == "YES":907 print(getString("private_key"), priv_key)908 else:909 print(getString("cancelled_invalid_confirmation"))910 elif wrong_passphrase:911 print(getString("error_wrong_passphrase"))912 else:913 print(getString("error_configure_wrapperconf"))914 elif command == "wsend":915 if use_wrapper:916 recipient = input(917 Style.RESET_ALL918 + Fore.WHITE919 + getString("enter_tron_recipients_name")920 + Style.BRIGHT)921 try:922 amount = float(input(923 Style.RESET_ALL924 + Fore.WHITE925 + getString("enter_amount_transfer")926 + Style.BRIGHT))927 except ValueError:928 print(getString("amount_numeric"))929 continue930 wbalance = float(wduco.functions.balanceOf(pub_key))/10**6931 if float(amount) <= wbalance:932 txn = wduco.functions.transfer(933 recipient,934 int(float(amount)*10**6)935 ).with_owner(936 pub_key937 ).fee_limit(938 5_000_000939 ).build().sign(940 PrivateKey(941 bytes.fromhex(priv_key)942 )943 )944 txn = txn.broadcast()945 print(getString("tron_transaction_submitted"),946 txn.txid)947 trontxresult = txn.wait()948 if trontxresult:949 print(getString("tron_successful_transaction"))950 else:951 print(getString("tron_error_transaction"))952 elif wrong_passphrase:953 print(getString("error_wrong_passphrase"))954 else:955 print(getString("error_configure_wrapperconf"))956 elif command == "about":957 print(Style.RESET_ALL958 + Fore.WHITE959 + getString("about_1"))960 print(Style.RESET_ALL961 + Fore.WHITE962 + getString("about_2")963 + str(VER))964 print(Style.RESET_ALL965 + Fore.WHITE966 + getString("about_3"))967 print(Style.RESET_ALL968 + Fore.WHITE969 + Style.BRIGHT970 + "https://duinocoin.com")971 print(Style.RESET_ALL972 + Fore.WHITE973 + getString("about_4")974 + Style.BRIGHT975 + str(SERVER_VER)976 + Style.RESET_ALL)977 if float(SERVER_VER) > VER:978 print(Style.RESET_ALL979 + Fore.YELLOW980 + getString("about_5")981 + Fore.WHITE982 + Style.BRIGHT983 + SERVER_VER984 + Fore.YELLOW985 + Style.RESET_ALL986 + getString("about_6")987 + Style.BRIGHT988 + Fore.WHITE989 + str(VER)990 + Style.RESET_ALL991 + Fore.YELLOW992 + getString("about_7"))993 else:994 print(Style.RESET_ALL995 + Fore.WHITE996 + getString("about_8"))997 elif command == "logout":998 os.remove(RESOURCES_DIR + "/CLIWallet_config.cfg")999 os.system("python " + __file__)1000 elif command == "donate":1001 print(Style.RESET_ALL1002 + Fore.BLUE1003 + Style.BRIGHT1004 + getString("donate_1"))1005 print(Style.RESET_ALL1006 + Fore.YELLOW1007 + getString("donate_2")1008 + Style.RESET_ALL1009 + Fore.WHITE1010 + Style.BRIGHT1011 + "TY5wfM6JsYKEEMfQR3RBQBPKfetTpf7nyM"1012 + Style.RESET_ALL1013 + Fore.YELLOW1014 + getString("donate_3"))1015 print("Duino-Coin: "1016 + Style.RESET_ALL1017 + Fore.WHITE1018 + Style.BRIGHT1019 + "revox"1020 + Style.RESET_ALL1021 + Fore.YELLOW1022 + getString("donate_4"))1023 print("Duino-Coin: "1024 + Style.RESET_ALL1025 + Fore.WHITE1026 + Style.BRIGHT1027 + "Yanis"1028 + Style.RESET_ALL1029 + Fore.YELLOW1030 + getString("donate_5"))1031 else:1032 print(Style.RESET_ALL1033 + Fore.YELLOW1034 + getString("duco_commands"))1035 print_commands_norm()1036 print(Style.RESET_ALL1037 + Fore.YELLOW1038 + getString("wrapper_commands"))...

Full Screen

Full Screen

Robot 1-0.py

Source:Robot 1-0.py Github

copy

Full Screen

1import ctre2import rev3import wpilib4from networktables import NetworkTables5class MyRobot(wpilib.TimedRobot):6 def robotInit(self):7 self.pdp = wpilib.PowerDistribution()8 self.bia = wpilib.BuiltInAccelerometer()9 self.driverstation = wpilib.DriverStation()10 NetworkTables.initialize()11 self.smartDash = NetworkTables.getTable("SmartDashboard")12 self.brownStain = False # Brownout Sustain13 self.brownoutDetection = True # Enable Brownout Detection14 # Define Things15 # TODO: Automate in the future: https://robotpy.readthedocs.io/projects/wpilib/en/stable/wpilib/CANStatus.html16 # TODO: Automate by scanning data https://robotpy.readthedocs.io/projects/wpilib/en/stable/wpilib/CANData.html17 self.prefs = wpilib.Preferences()18 if self.prefs.containsKey("Spark_Max_Brushed"):19 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(int(self.prefs.getString("Spark_Max_Brushed")))20 else:21 self.prefs.initString("Front_Left_Motor", "0")22 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(0) # 0 is Brushed and 1 is Brushless23 if self.prefs.containsKey("Front_Left_Motor"):24 if self.prefs.containsKey("Front_Left_Motor_ID"):25 pass26 else:27 self.prefs.initInt("Front_Left_Motor", "0")28 if self.prefs.getString("Front_Left_Motor") == "Spark_Max":29 self._Front_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Left_Motor_ID")), self.CANSparkMaxType)30 elif self.prefs.getString("Front_Left_Motor") == "Talon_FX":31 self._Front_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Left_Motor_ID")))32 elif self.prefs.getString("Front_Left_Motor") == "Talon_SRX":33 self._Front_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Left_Motor_ID")))34 elif self.prefs.getString("Front_Left_Motor") == "Victor_SPX":35 self._Front_Left_Motor = ctre.VictorSPX(int(self.prefs.getString("Front_Left_Motor_ID")))36 else:37 self.prefs.initString("Front_Left_Motor", "Spark_Max")38 self._Front_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Left_Motor_ID")), self.CANSparkMaxType)39 if self.prefs.containsKey("Front_Right_Motor"):40 if self.prefs.containsKey("Front_Right_Motor_ID"):41 pass42 else:43 self.prefs.initInt("Front_Right_Motor", "1")44 if self.prefs.getString("Front_Right_Motor") == "Spark_Max":45 self._Front_Right_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Right_Motor_ID")), self.CANSparkMaxType)46 elif self.prefs.getString("Front_Right_Motor") == "Talon_FX":47 self._Front_Right_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Right_Motor_ID")))48 elif self.prefs.getString("Front_Right_Motor") == "Talon_SRX":49 self._Front_Right_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Right_Motor_ID")))50 elif self.prefs.getString("Front_Right_Motor") == "Victor_SPX":51 self._Front_Right_Motor = ctre.VictorSPX(int(self.prefs.getString("Front_Right_Motor_ID")))52 else:53 self.prefs.initString("Front_Right_Motor", "Spark_Max")54 self._Front_Right_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Right_Motor_ID")), self.CANSparkMaxType)55 if self.prefs.containsKey("Back_Right_Motor"):56 if self.prefs.containsKey("Back_Right_Motor_ID"):57 pass58 else:59 self.prefs.initInt("Back_Right_Motor", "2")60 if self.prefs.getString("Back_Right_Motor") == "Spark_Max":61 self._Back_Right_Motor = rev.CANSparkMax(int(self.prefs.getString("Back_Right_Motor_ID")), self.CANSparkMaxType)62 elif self.prefs.getString("Back_Right_Motor") == "Talon_FX":63 self._Back_Right_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Right_Motor_ID")))64 elif self.prefs.getString("Back_Right_Motor") == "Talon_SRX":65 self._Back_Right_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Right_Motor_ID")))66 elif self.prefs.getString("Back_Right_Motor") == "Victor_SPX":67 self._Back_Right_Motor = ctre.VictorSPX(int(self.prefs.getString("Back_Right_Motor_ID")))68 else:69 self.prefs.initString("Back_Right_Motor", "Spark_Max")70 self._Back_Right_Motor = rev.CANSparkMax(int(self.prefs.getString("Back_Right_Motor_ID")), self.CANSparkMaxType)71 if self.prefs.containsKey("Back_Left_Motor"):72 if self.prefs.containsKey("Back_Left_Motor_ID"):73 pass74 else:75 self.prefs.initInt("Back_Left_Motor", "3")76 if self.prefs.getString("Back_Left_Motor") == "Spark_Max":77 self._Back_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Back_Left_Motor_ID")), self.CANSparkMaxType)78 elif self.prefs.getString("Back_Left_Motor") == "Talon_FX":79 self._Back_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Left_Motor_ID")))80 elif self.prefs.getString("Back_Left_Motor") == "Talon_SRX":81 self._Back_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Left_Motor_ID")))82 elif self.prefs.getString("Back_Left_Motor") == "Victor_SPX":83 self._Back_Left_Motor = ctre.VictorSPX(int(self.prefs.getString("Back_Left_Motor_ID")))84 else:85 self.prefs.initString("Back_Left_Motor", "Spark_Max")86 self._Back_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Back_Left_Motor_ID")), self.CANSparkMaxType)87 if self.prefs.containsKey("Shooter_Motor"):88 if self.prefs.containsKey("Shooter_Motor_ID"):89 pass90 else:91 self.prefs.initInt("Shooter_Motor", "4")92 if self.prefs.getString("Shooter_Motor") == "Spark_Max":93 self._Shooter_Motor = rev.CANSparkMax(int(self.prefs.getString("Shooter_Motor_ID")), self.CANSparkMaxType)94 elif self.prefs.getString("Shooter_Motor") == "Talon_FX":95 self._Shooter_Motor = ctre.TalonFX(int(self.prefs.getString("Shooter_Motor_ID")))96 elif self.prefs.getString("Shooter_Motor") == "Talon_SRX":97 self._Shooter_Motor = ctre.TalonSRX(int(self.prefs.getString("Shooter_Motor_ID")))98 elif self.prefs.getString("Shooter_Motor") == "Victor_SPX":99 self._Shooter_Motor = ctre.VictorSPX(int(self.prefs.getString("Shooter_Motor_ID")))100 else:101 self.prefs.initString("Shooter_Motor", "Talon_FX")102 self._Shooter_Motor = ctre.TalonFX(int(self.prefs.getString("Shooter_Motor_ID")))103 if self.prefs.containsKey("Intake_Motor"):104 if self.prefs.containsKey("Intake_Motor_ID"):105 pass106 else:107 self.prefs.initInt("Intake_Motor", "5")108 if self.prefs.getString("Intake_Motor") == "Spark_Max":109 self._Intake_Motor = rev.CANSparkMax(int(self.prefs.getString("Intake_Motor_ID")), self.CANSparkMaxType)110 elif self.prefs.getString("Intake_Motor") == "Talon_FX":111 self._Intake_Motor = ctre.TalonFX(int(self.prefs.getString("Intake_Motor_ID")))112 elif self.prefs.getString("Intake_Motor") == "Talon_SRX":113 self._Intake_Motor = ctre.TalonSRX(int(self.prefs.getString("Intake_Motor_ID")))114 elif self.prefs.getString("Intake_Motor") == "Victor_SPX":115 self._Intake_Motor = ctre.VictorSPX(int(self.prefs.getString("Intake_Motor_ID")))116 else:117 self.prefs.initString("Intake_Motor", "Talon_SRX")118 self._Intake_Motor = ctre.TalonSRX(int(self.prefs.getString("Intake_Motor_ID")))119 # Start Network Tables Stuff120 def getNetworkTables():121 # Define Dynamic values122 # TODO: Make update rate a non-persistant variable https://robotpy.readthedocs.io/projects/pynetworktables/en/stable/api.html#networktables.NetworkTablesInstance.setUpdateRate123 nonlocal self124 entries = self.smartDash.getEntries("")125 for preference in self.prefs.getKeys():126 if preference not in entries:127 self.smartDash.setDefaultString(str(preference), self.prefs.getString(preference))128 else:129 if self.smartDash.getString(preference) != self.prefs.getString(preference):130 if preference == "Front_Left_Motor":131 if self.smartDash.getString(preference) == "Spark_Max":132 self._Front_Left_Motor = rev.CANSparkMax(133 int(self.prefs.getString("Front_Left_Motor_ID")), self.CANSparkMaxType)134 elif self.smartDash.getString(preference) == "Talon_FX":135 self._Front_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Left_Motor_ID")))136 elif self.smartDash.getString(preference) == "Talon_SRX":137 self._Front_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Left_Motor_ID")))138 elif self.smartDash.getString(preference) == "Victor_SPX":139 self._Front_Left_Motor = ctre.VictorSPX(140 int(self.prefs.getString("Front_Left_Motor_ID")))141 else:142 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")143 if preference == "Front_Right_Motor":144 if self.smartDash.getString(preference) == "Spark_Max":145 self._Front_Right_Motor = rev.CANSparkMax(146 int(self.prefs.getString("Front_Right_Motor_ID")), self.CANSparkMaxType)147 elif self.smartDash.getString(preference) == "Talon_FX":148 self._Front_Right_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Right_Motor_ID")))149 elif self.smartDash.getString(preference) == "Talon_SRX":150 self._Front_Right_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Right_Motor_ID")))151 elif self.smartDash.getString(preference) == "Victor_SPX":152 self._Front_Right_Motor = ctre.VictorSPX(153 int(self.prefs.getString("Front_Right_Motor_ID")))154 else:155 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")156 if preference == "Back_Left_Motor":157 if self.smartDash.getString(preference) == "Spark_Max":158 self._Back_Left_Motor = rev.CANSparkMax(159 int(self.prefs.getString("Back_Left_Motor_ID")), self.CANSparkMaxType)160 elif self.smartDash.getString(preference) == "Talon_FX":161 self._Back_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Left_Motor_ID")))162 elif self.smartDash.getString(preference) == "Talon_SRX":163 self._Back_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Left_Motor_ID")))164 elif self.smartDash.getString(preference) == "Victor_SPX":165 self._Back_Left_Motor = ctre.VictorSPX(166 int(self.prefs.getString("Back_Left_Motor_ID")))167 else:168 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")169 if preference == "Back_Right_Motor":170 if self.smartDash.getString(preference) == "Spark_Max":171 self._Back_Right_Motor = rev.CANSparkMax(172 int(self.prefs.getString("Back_Right_Motor_ID")), self.CANSparkMaxType)173 elif self.smartDash.getString(preference) == "Talon_FX":174 self._Back_Right_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Right_Motor_ID")))175 elif self.smartDash.getString(preference) == "Talon_SRX":176 self._Back_Right_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Right_Motor_ID")))177 elif self.smartDash.getString(preference) == "Victor_SPX":178 self._Back_Right_Motor = ctre.VictorSPX(179 int(self.prefs.getString("Back_Right_Motor_ID")))180 else:181 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")182 if preference == "Shooter_Motor":183 if self.smartDash.getString(preference) == "Spark_Max":184 self._Shooter_Motor = rev.CANSparkMax(185 int(self.prefs.getString("Shooter_Motor_ID")), self.CANSparkMaxType)186 elif self.smartDash.getString(preference) == "Talon_FX":187 self._Shooter_Motor = ctre.TalonFX(int(self.prefs.getString("Shooter_Motor_ID")))188 elif self.smartDash.getString(preference) == "Talon_SRX":189 self._Shooter_Motor = ctre.TalonSRX(int(self.prefs.getString("Shooter_Motor_ID")))190 elif self.smartDash.getString(preference) == "Victor_SPX":191 self._Shooter_Motor = ctre.VictorSPX(192 int(self.prefs.getString("Shooter_Motor_ID")))193 else:194 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")195 if preference == "Intake_Motor":196 if self.smartDash.getString(preference) == "Spark_Max":197 self._Intake_Motor = rev.CANSparkMax(198 int(self.prefs.getString("Intake_Motor_ID")), self.CANSparkMaxType)199 elif self.smartDash.getString(preference) == "Talon_FX":200 self._Intake_Motor = ctre.TalonFX(int(self.prefs.getString("Intake_Motor_ID")))201 elif self.smartDash.getString(preference) == "Talon_SRX":202 self._Intake_Motor = ctre.TalonSRX(int(self.prefs.getString("Intake_Motor_ID")))203 elif self.smartDash.getString(preference) == "Victor_SPX":204 self._Intake_Motor = ctre.VictorSPX(205 int(self.prefs.getString("Intake_Motor_ID")))206 else:207 self.smartDash.putString(preference, f"Invalid String - Defaulted to {self.prefs.getString(preference)}")208 if preference == "Spark_Max_Brushed":209 if self.prefs.containsKey("Spark_Max_Brushed"):210 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(211 int(self.prefs.getString("Spark_Max_Brushed")))212 else:213 self.prefs.initString("Front_Left_Motor", "0")214 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(215 0) # 0 is Brushed and 1 is Brushless216 # Brownout Stuff217 if "Brownout_Detection" not in entries:218 self.smartDash.putValue("Brownout_Detection", True)219 # Define Static Variables220 if self.smartDash.containsKey("PDP_Total_Output_Joules"):221 self.smartDash.putValue("PDP_Total_Output_Joules", self.pdp.getTotalEnergy())222 else:223 self.smartDash.setDefaultValue("PDP_Total_Output_Joules", 0)224 if self.smartDash.containsKey("PDP_Temperature_Fahrenheit"):225 self.smartDash.putValue("PDP_Temperature_Fahrenheit", self.pdp.getTemperature())226 else:227 self.smartDash.setDefaultValue("PDP_Temperature_Fahrenheit", 0)228 if self.smartDash.containsKey("PDP_Total_Output_Amperage"):229 self.smartDash.putValue("PDP_Total_Output_Amperage", self.pdp.getTotalCurrent())230 else:231 self.smartDash.setDefaultValue("PDP_Total_Output_Amperage", 0)232 if self.smartDash.containsKey("PDP_Total_Output_Watts"):233 self.smartDash.putValue("PDP_Total_Output_Watts", self.pdp.getTotalPower())234 else:235 self.smartDash.setDefaultValue("PDP_Total_Output_Watts", 0)236 if self.smartDash.containsKey("PDP_Input_Voltage"):237 self.smartDash.putValue("PDP_Input_Voltage", self.pdp.getVoltage())238 else:239 self.smartDash.setDefaultValue("PDP_Input_Voltage", 0)240 if self.smartDash.containsKey("Battery_Percentage"):241 self.smartDash.putValue("Battery_Percentage", (self.pdp.getVoltage()-6.8)/5.2)242 else:243 self.smartDash.setDefaultValue("Battery_Percentage", 0)244 if self.smartDash.containsKey("RIO_Int_Accelerometer_XValue_MpS^2"):245 self.smartDash.putValue("RIO_Int_Accelerometer_XValue_MpS^2", self.bia.getX())246 else:247 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_XValue_MpS^2", 0)248 if self.smartDash.containsKey("RIO_Int_Accelerometer_YValue_MpS^2"):249 self.smartDash.putValue("RIO_Int_Accelerometer_YValue_MpS^2", self.bia.getY())250 else:251 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_YValue_MpS^2", 0)252 if self.smartDash.containsKey("RIO_Int_Accelerometer_ZValue_MpS^2"):253 self.smartDash.putValue("RIO_Int_Accelerometer_ZValue_MpS^2", self.bia.getZ())254 else:255 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_ZValue_MpS^2", 0)256 def brownoutDetection():257 nonlocal self258 if self.smartDash.getValue("Brownout_Detection"):259 if self.smartDash.containsKey("Brownout"):260 if self.driverstation.getBatteryVoltage() < 6.8:261 self.smartDash.putValue("Brownout", "BROWNOUT WARNING")262 self._Front_Left_Motor.set(0)263 self._Front_Right_Motor.set(0)264 self._Back_Right_Motor.set(0)265 self._Back_Left_Motor.set(0)266 self._Shooter_Motor.set(0)267 self._Intake_Motor.set(0)268 else:269 self.smartDash.setDefaultValue("Brownout", "Not Detected")270 else:271 self.smartDash.delete("Brownout")272 # Initialize Network Tables Interaction 2 seconds after init. Cycles every 0.25 seconds273 self.addPeriodic(getNetworkTables, 0.25, offset=2)274 # Flush Data every 5 seconds for synchronizing network updates275 self.addPeriodic(NetworkTables.flush, 5)276 # Initialize Brownout Detection 1 seconds after init. Cycles every 0.25 seconds277 self.addPeriodic(brownoutDetection, 0.25, offset=1)278 # Define Game Stuff getJoystickIsXbox()279 self.controller = wpilib.XboxController(0)280 self.timer = wpilib.Timer()281 def autonomousInit(self):282 """This function is run once each time the robot enters autonomous mode."""283 self.timer.reset()284 self.timer.start()285 def autonomousPeriodic(self):286 """This function is called periodically during autonomous."""287 # Drive for two seconds288 # if self.timer.get() < 2.0:289 # self.drive.arcadeDrive(-0.5, 0) # Drive forwards at half speed290 # else:291 # self.drive.arcadeDrive(0, 0) # Stop robot292 def teleopPeriodic(self):293 # TODO: Implement pnumatics and climber boi294 self._Shooter_Motor.set(self.controller.getRightTriggerAxis())295 self._Intake_Motor.set(self.controller.getLeftTriggerAxis())296 self._Back_Left_Motor.set(self.controller.getLeftY())297 self._Front_Left_Motor.set(self.controller.getLeftY())298 self._Back_Right_Motor.set(self.controller.getRightY())299 self._Front_Right_Motor.set(self.controller.getRightY())300if __name__ == "__main__":...

Full Screen

Full Screen

Robot.py

Source:Robot.py Github

copy

Full Screen

1import ctre2import pyfrc.tests3import rev4import wpilib5from networktables import NetworkTables6from pyfrc.tests import *7class MyRobot(wpilib.TimedRobot):8 def robotInit(self):9 self.pdp = wpilib.PowerDistribution()10 self.bia = wpilib.BuiltInAccelerometer()11 self.pcm = wpilib.PneumaticsControlModule()12 NetworkTables.initialize()13 self.smartDash = NetworkTables.getTable("SmartDashboard")14 self.brownoutDetection = True # Enable Brownout Detection15 # Define Things16 if self.pcm.getCompressor():17 self.compressor = wpilib.Compressor(moduleType=self.pcm.getCompressorConfigType())18 self.solenoid = self.pcm.makeSolenoid(1) # Solenoid Number19 else:20 wpilib.reportWarning("Compressor Not Found!!!")21 # Controller stuff: self.Controller_Controllers = {"RightSide": }22 self.Motor_Controllers = {1: "RightSide", 9: "Shooter", 11: "Elevator", 2: "LeftSide", 5: "Intake"}23 self.CAN_Motors = []24 # Get all Motors25 for x in range(1, 64):26 try:27 self.CAN_Motors.append({"Object": rev.CANSparkMax(deviceID=x, type=rev.CANSparkMaxLowLevel.MotorType(0)), "Type": "SparkMax", "ID": x}) # 0 is brushed 1 is brushless28 except:29 pass30 try:31 self.CAN_Motors.append({"Object": ctre.TalonFX(x), "Type": "TalonFX", "ID": x})32 except:33 self.CAN_Motors.append({"Object": ctre.TalonSRX(x), "Type": "TalonSRX", "ID": x})34 try:35 self.CAN_Motors.append({"Object": ctre.VictorSPX(x), "Type": "VictorSPX", "ID": x})36 except:37 pass38 self.prefs = wpilib.Preferences()39 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(0) # 0 is Brushed and 1 is Brushless40 if self.prefs.containsKey("Front_Left_Motor"):41 if self.prefs.containsKey("Front_Left_Motor_ID"):42 pass43 else:44 self.prefs.initInt("Front_Left_Motor", "0")45 if self.prefs.getString("Front_Left_Motor") == "Spark_Max":46 self._Front_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Left_Motor_ID")),47 self.CANSparkMaxType)48 elif self.prefs.getString("Front_Left_Motor") == "Talon_FX":49 self._Front_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Left_Motor_ID")))50 elif self.prefs.getString("Front_Left_Motor") == "Talon_SRX":51 self._Front_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Left_Motor_ID")))52 elif self.prefs.getString("Front_Left_Motor") == "Victor_SPX":53 self._Front_Left_Motor = ctre.VictorSPX(int(self.prefs.getString("Front_Left_Motor_ID")))54 else:55 self.prefs.initString("Front_Left_Motor", "Spark_Max")56 self._Front_Left_Motor = rev.CANSparkMax(int(self.prefs.getString("Front_Left_Motor_ID")),57 self.CANSparkMaxType)58 # Start Network Tables Stuff59 def getNetworkTables():60 nonlocal self61 entries = self.smartDash.getEntries("")62 for preference in self.prefs.getKeys():63 if preference not in entries:64 self.smartDash.setDefaultString(str(preference), self.prefs.getString(preference))65 else:66 if self.smartDash.getString(preference) != self.prefs.getString(preference):67 if preference == "Front_Left_Motor":68 if self.smartDash.getString(preference) == "Spark_Max":69 self._Front_Left_Motor = rev.CANSparkMax(70 int(self.prefs.getString("Front_Left_Motor_ID")), self.CANSparkMaxType)71 elif self.smartDash.getString(preference) == "Talon_FX":72 self._Front_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Front_Left_Motor_ID")))73 elif self.smartDash.getString(preference) == "Talon_SRX":74 self._Front_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Front_Left_Motor_ID")))75 elif self.smartDash.getString(preference) == "Victor_SPX":76 self._Front_Left_Motor = ctre.VictorSPX(77 int(self.prefs.getString("Front_Left_Motor_ID")))78 else:79 self.smartDash.putString(preference,80 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")81 if preference == "Front_Right_Motor":82 if self.smartDash.getString(preference) == "Spark_Max":83 self._Front_Right_Motor = rev.CANSparkMax(84 int(self.prefs.getString("Front_Right_Motor_ID")), self.CANSparkMaxType)85 elif self.smartDash.getString(preference) == "Talon_FX":86 self._Front_Right_Motor = ctre.TalonFX(87 int(self.prefs.getString("Front_Right_Motor_ID")))88 elif self.smartDash.getString(preference) == "Talon_SRX":89 self._Front_Right_Motor = ctre.TalonSRX(90 int(self.prefs.getString("Front_Right_Motor_ID")))91 elif self.smartDash.getString(preference) == "Victor_SPX":92 self._Front_Right_Motor = ctre.VictorSPX(93 int(self.prefs.getString("Front_Right_Motor_ID")))94 else:95 self.smartDash.putString(preference,96 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")97 if preference == "Back_Left_Motor":98 if self.smartDash.getString(preference) == "Spark_Max":99 self._Back_Left_Motor = rev.CANSparkMax(100 int(self.prefs.getString("Back_Left_Motor_ID")), self.CANSparkMaxType)101 elif self.smartDash.getString(preference) == "Talon_FX":102 self._Back_Left_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Left_Motor_ID")))103 elif self.smartDash.getString(preference) == "Talon_SRX":104 self._Back_Left_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Left_Motor_ID")))105 elif self.smartDash.getString(preference) == "Victor_SPX":106 self._Back_Left_Motor = ctre.VictorSPX(107 int(self.prefs.getString("Back_Left_Motor_ID")))108 else:109 self.smartDash.putString(preference,110 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")111 if preference == "Back_Right_Motor":112 if self.smartDash.getString(preference) == "Spark_Max":113 self._Back_Right_Motor = rev.CANSparkMax(114 int(self.prefs.getString("Back_Right_Motor_ID")), self.CANSparkMaxType)115 elif self.smartDash.getString(preference) == "Talon_FX":116 self._Back_Right_Motor = ctre.TalonFX(int(self.prefs.getString("Back_Right_Motor_ID")))117 elif self.smartDash.getString(preference) == "Talon_SRX":118 self._Back_Right_Motor = ctre.TalonSRX(int(self.prefs.getString("Back_Right_Motor_ID")))119 elif self.smartDash.getString(preference) == "Victor_SPX":120 self._Back_Right_Motor = ctre.VictorSPX(121 int(self.prefs.getString("Back_Right_Motor_ID")))122 else:123 self.smartDash.putString(preference,124 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")125 if preference == "Shooter_Motor":126 if self.smartDash.getString(preference) == "Spark_Max":127 self._Shooter_Motor = rev.CANSparkMax(128 int(self.prefs.getString("Shooter_Motor_ID")), self.CANSparkMaxType)129 elif self.smartDash.getString(preference) == "Talon_FX":130 self._Shooter_Motor = ctre.TalonFX(int(self.prefs.getString("Shooter_Motor_ID")))131 elif self.smartDash.getString(preference) == "Talon_SRX":132 self._Shooter_Motor = ctre.TalonSRX(int(self.prefs.getString("Shooter_Motor_ID")))133 elif self.smartDash.getString(preference) == "Victor_SPX":134 self._Shooter_Motor = ctre.VictorSPX(135 int(self.prefs.getString("Shooter_Motor_ID")))136 else:137 self.smartDash.putString(preference,138 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")139 if preference == "Intake_Motor":140 if self.smartDash.getString(preference) == "Spark_Max":141 self._Intake_Motor = rev.CANSparkMax(142 int(self.prefs.getString("Intake_Motor_ID")), self.CANSparkMaxType)143 elif self.smartDash.getString(preference) == "Talon_FX":144 self._Intake_Motor = ctre.TalonFX(int(self.prefs.getString("Intake_Motor_ID")))145 elif self.smartDash.getString(preference) == "Talon_SRX":146 self._Intake_Motor = ctre.TalonSRX(int(self.prefs.getString("Intake_Motor_ID")))147 elif self.smartDash.getString(preference) == "Victor_SPX":148 self._Intake_Motor = ctre.VictorSPX(149 int(self.prefs.getString("Intake_Motor_ID")))150 else:151 self.smartDash.putString(preference,152 f"Invalid String - Defaulted to {self.prefs.getString(preference)}")153 if preference == "Spark_Max_Brushed":154 if self.prefs.containsKey("Spark_Max_Brushed"):155 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(156 int(self.prefs.getString("Spark_Max_Brushed")))157 else:158 self.prefs.initString("Front_Left_Motor", "0")159 self.CANSparkMaxType = rev.CANSparkMaxLowLevel.MotorType(160 0) # 0 is Brushed and 1 is Brushless161 # Brownout Stuff162 if "Brownout_Detection" not in entries:163 self.smartDash.putValue("Brownout_Detection", True)164 # Define Static Variables165 if self.smartDash.containsKey("PDP_Total_Output_Joules"):166 self.smartDash.putValue("PDP_Total_Output_Joules", self.pdp.getTotalEnergy())167 else:168 self.smartDash.setDefaultValue("PDP_Total_Output_Joules", 0)169 if self.smartDash.containsKey("PDP_Temperature_Fahrenheit"):170 self.smartDash.putValue("PDP_Temperature_Fahrenheit", self.pdp.getTemperature())171 else:172 self.smartDash.setDefaultValue("PDP_Temperature_Fahrenheit", 0)173 if self.smartDash.containsKey("PDP_Total_Output_Amperage"):174 self.smartDash.putValue("PDP_Total_Output_Amperage", self.pdp.getTotalCurrent())175 else:176 self.smartDash.setDefaultValue("PDP_Total_Output_Amperage", 0)177 if self.smartDash.containsKey("PDP_Total_Output_Watts"):178 self.smartDash.putValue("PDP_Total_Output_Watts", self.pdp.getTotalPower())179 else:180 self.smartDash.setDefaultValue("PDP_Total_Output_Watts", 0)181 if self.smartDash.containsKey("PDP_Input_Voltage"):182 self.smartDash.putValue("PDP_Input_Voltage", self.pdp.getVoltage())183 else:184 self.smartDash.setDefaultValue("PDP_Input_Voltage", 0)185 if self.smartDash.containsKey("Battery_Percentage"):186 self.smartDash.putValue("Battery_Percentage", (self.pdp.getVoltage() - 6.8) / 5.2)187 else:188 self.smartDash.setDefaultValue("Battery_Percentage", 0)189 if self.smartDash.containsKey("RIO_Int_Accelerometer_XValue_MpS^2"):190 self.smartDash.putValue("RIO_Int_Accelerometer_XValue_MpS^2", self.bia.getX())191 else:192 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_XValue_MpS^2", 0)193 if self.smartDash.containsKey("RIO_Int_Accelerometer_YValue_MpS^2"):194 self.smartDash.putValue("RIO_Int_Accelerometer_YValue_MpS^2", self.bia.getY())195 else:196 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_YValue_MpS^2", 0)197 if self.smartDash.containsKey("RIO_Int_Accelerometer_ZValue_MpS^2"):198 self.smartDash.putValue("RIO_Int_Accelerometer_ZValue_MpS^2", self.bia.getZ())199 else:200 self.smartDash.setDefaultValue("RIO_Int_Accelerometer_ZValue_MpS^2", 0)201 def brownoutDetection():202 nonlocal self203 if self.smartDash.getValue("Brownout_Detection"):204 if self.smartDash.containsKey("Brownout"):205 if wpilib.DriverStation.getBatteryVoltage() < 6.8:206 self.smartDash.putValue("Brownout", "BROWNOUT WARNING")207 for motor in self.CAN_Motors:208 # ctre.ControlMode.PercentOutput209 if motor["Type"] != "SparkMax":210 motor["Object"].set(ctre.ControlMode.PercentOutput, 0)211 else:212 motor["Object"].set(0)213 else:214 self.smartDash.setDefaultValue("Brownout", "Not Detected")215 else:216 self.smartDash.delete("Brownout")217 # Initialize Network Tables Interaction 2 seconds after init. Cycles every 0.25 seconds218 self.addPeriodic(getNetworkTables, 0.25, offset=2)219 # Flush Data every 5 seconds for synchronizing network updates220 self.addPeriodic(NetworkTables.flush, 5)221 # Initialize Brownout Detection 1 seconds after init. Cycles every 0.25 seconds222 self.addPeriodic(brownoutDetection, 0.25, offset=1)223 # Define Game Stuff224 self.timer = wpilib.Timer()225 def disabledInit(self):226 if self.compressor.getPressure() > self.safePSI:227 self.compressor.stop()228 else:229 self.compressor.start()230 for motor in self.CAN_Motors:231 if motor["Type"] != "SparkMax":232 motor["Object"].set(ctre.ControlMode.PercentOutput, 0)233 else:234 motor["Object"].set(0)235 def disabledPeriodic(self):236 if self.compressor.getPressure() > self.safePSI:237 self.compressor.stop()238 else:239 self.compressor.start()240 for motor in self.CAN_Motors:241 if motor["Type"] != "SparkMax":242 motor["Object"].set(ctre.ControlMode.PercentOutput, 0)243 else:244 motor["Object"].set(0)245 def autonomousInit(self):246 """This function is run once each time the robot enters autonomous mode."""247 self.timer.reset()248 self.timer.start()249 def autonomousPeriodic(self):250 """This function is called periodically during autonomous."""251 # Drive for two seconds252 # if self.timer.get() < 2.0:253 # self.drive.arcadeDrive(-0.5, 0) # Drive forwards at half speed254 # else:255 # self.drive.arcadeDrive(0, 0) # Stop robot256 def teleopPeriodic(self):257 # TODO: Get pressure rating258 if self.compressor.getPressure() > self.safePSI:259 self.compressor.stop()260 else:261 self.compressor.start()262 # self.Motor_Controllers = {1: "RightSide", 9: "Shooter", 11: "Elevator", 2: "LeftSide", 5: "Intake"}263 for motor in self.CAN_Motors:264 # ctre.ControlMode.PercentOutput265 if motor["Type"] != "SparkMax":266 motor["Object"].set(ctre.ControlMode.PercentOutput, 0)267 else:268 motor["Object"].set(0)269 # If Controller Button: self.solenoid.toggle()270if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tox automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful