Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added in the wifi examples from another branch #683

Merged
merged 6 commits into from
Feb 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions micropython/examples/cosmic_unicorn/exchange_ticker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""
This example uses the Coinbase open API to collect the current exchange rates.
Use Switch A to change to a different base exchange currency.
"""

import WIFI_CONFIG
from network_manager import NetworkManager
import uasyncio
import urequests
import time
import math
from cosmic import CosmicUnicorn
from picographics import PicoGraphics, DISPLAY_COSMIC_UNICORN as DISPLAY
import gc

URL = 'https://api.coinbase.com/v2/exchange-rates?currency={0}'

currencies = {"Bitcoin": "BTC", "Ethereun": "ETH", "Pound": "GBP", "Dollar": "USD", "Dogecoin": "DOGE"}
currency_keys = list(currencies.keys())

ref_currency_name = ""
currency_name = ""
currency_symbol = ""
currency_rate = ""
rate_keys = []

# diplay options
line_1_line = -2
line_2_line = 9
line_3_line = 20

ref_currency_index = 0

cycles_per_sequence = 120

cu = CosmicUnicorn()
graphics = PicoGraphics(DISPLAY)


# for Handling the wifi connection
def status_handler(mode, status, ip):
# reports wifi connection status
print(mode, status, ip)
print('Connecting to wifi...')
if status is not None:
if status:
print('Wifi connection successful!')
else:
print('Wifi connection failed!')


try:
network_manager = NetworkManager(WIFI_CONFIG.COUNTRY, status_handler=status_handler)
uasyncio.get_event_loop().run_until_complete(network_manager.client(WIFI_CONFIG.SSID, WIFI_CONFIG.PSK))
except Exception as e:
print(f'Wifi connection failed! {e}')


def get_data(currency_selected):

graphics.set_pen(graphics.create_pen(20, 20, 20))
graphics.clear()
graphics.set_pen(graphics.create_pen(100, 100, 100))
graphics.text("Get", 0, 10, scale=1, spacing=1)
graphics.text("data", 8, 16, scale=1, spacing=1)
cu.update(graphics)
gc.collect()
# open the json file
print('Requesting URL:')
print(URL.format(currencies[currency_selected]))
r = urequests.get(URL.format(currencies[currency_selected]))
gc.collect()
# open the json data
data_obj = r.json()
print('Data obtained!')
r.close()
return data_obj


def calculate_xpos(length, cycle):
cycle_phase = math.cos(math.pi * cycle / (cycles_per_sequence / 2))
pos_x = int((-(length / 2) * 10) - (length / 2) * 10 * cycle_phase)
return pos_x


def update_display(cycle):

graphics.set_pen(graphics.create_pen(20, 20, 20))
graphics.clear()
graphics.set_pen(graphics.create_pen(100, 0, 0))
graphics.text(ref_currency_name, calculate_xpos((len(ref_currency_name)), cycle), line_1_line, scale=2, spacing=1)
graphics.set_pen(graphics.create_pen(100, 100, 0))
if len(currency_symbol) > 3:
graphics.text(currency_symbol, calculate_xpos((len(currency_symbol)), cycle), line_2_line, scale=2, spacing=1)
else:
graphics.text(currency_symbol, 0, line_2_line, scale=2, spacing=1)
graphics.set_pen(graphics.create_pen(0, 100, 100))
graphics.text(currency_rate, calculate_xpos((len(currency_rate)), cycle), line_3_line, scale=2, spacing=1)


def update_base_currency(index):
fetched_data = 0
global rates, rate_keys, currency_symbol, currency_rate, ref_currency_name
fetched_data = get_data(currency_keys[index])
rates = fetched_data['data']['rates']
rate_keys = list(rates.keys())
currency_symbol = rate_keys[index]
currency_rate = str(rates[rate_keys[index]])
ref_currency_name = "{0}-{1}".format(currency_keys[index], currencies[currency_keys[index]])
gc.collect()


update_base_currency(ref_currency_index)
update_display(0)
cu.update(graphics)
cycle_count = 0
symbol_index = 0
print("Display {0} {1}".format(currency_symbol, currency_rate))

while 1:
if cycle_count > 4 * cycles_per_sequence:
cycle_count = 0
symbol_index += 1
if symbol_index > len(currency_keys):
symbol_index = 0
print("Display {0} {1}".format(currency_symbol, currency_rate))
currency_symbol = rate_keys[symbol_index]
currency_rate = rates[rate_keys[symbol_index]]

if (cu.is_pressed(CosmicUnicorn.SWITCH_A)):
ref_currency_index += 1
if (ref_currency_index > len(currency_keys)):
ref_currency_index = 0
update_base_currency(ref_currency_index)

if (cu.is_pressed(CosmicUnicorn.SWITCH_B)):
cycle_count = 0
symbol_index += 1

if symbol_index > len(rate_keys):
symbol_index = 0
currency_symbol = rate_keys[symbol_index]
currency_rate = rates[rate_keys[symbol_index]]

update_display(cycle_count)
cu.update(graphics)
cycle_count += 1
time.sleep(0.1)
198 changes: 198 additions & 0 deletions micropython/examples/cosmic_unicorn/http_text/html_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import time
from cosmic import CosmicUnicorn
from picographics import PicoGraphics, DISPLAY_COSMIC_UNICORN as DISPLAY
import WIFI_CONFIG
from network_manager import NetworkManager
import uasyncio as asyncio
import uasyncio.core
from tinyweb.server import webserver

'''
Display scrolling wisdom, quotes or greetz... from the internetz!

You can adjust the brightness with LUX + and -.

Requires network_manager.py , WIFI_CONFIG.py, logging.mpy and tinyweb from micropython/examples/common
You'll also need index.html to be saved alongside this file.
'''

# Server Settings
host = "0.0.0.0"
port = 80


def convert_colour(colour_str):
colour_str = colour_str.split(',')
print(colour_str)
return colour_str[0], colour_str[1], colour_str[2]


class text:

def get(self, data):
global MESSAGE, MESSAGE_COLOUR, BACKGROUND_COLOUR
print(data)
if 'text' in data.keys():
MESSAGE = data['text']
if 'colourfg' in data.keys():
MESSAGE_COLOUR = convert_colour(data['colourfg'])
if 'colourbg' in data.keys():
BACKGROUND_COLOUR = convert_colour(data['colourbg'])
return {'message': 'text updated'}, 201

def post(self, data):

return {'message': 'text updated'}, 201


def status_handler(mode, status, ip):
global MESSAGE
print("Network: {}".format(WIFI_CONFIG.SSID))
status_text = "Connecting..."
if status is not None:
if status:
status_text = "Connection successful!"
else:
status_text = "Connection failed!"

print(status_text)
print("IP: {}".format(ip))
MESSAGE = "{}".format(ip)


# Create web server application
app = webserver()

# Static page
html_file = open('index.html', 'r')

# WIFI settings
WIFI_COUNTRY = "GB" # Changeme!


# Index page
@app.route('/')
async def index(request, response):
# Start HTTP response with content-type text/html
await response.start_html()
# Send actual HTML page
await response.send(html_file.read())


# HTTP redirection
@app.route('/redirect')
async def redirect(request, response):
# Start HTTP response with content-type text/html
await response.redirect('/')

# constants for controlling scrolling text
PADDING = 5
MESSAGE_COLOUR = (255, 255, 255)
OUTLINE_COLOUR = (0, 0, 0)
BACKGROUND_COLOUR = (10, 0, 96)
MESSAGE = "Connecting"
HOLD_TIME = 2.0
STEP_TIME = 0.075

# create galactic object and graphics surface for drawing
cu = CosmicUnicorn()
graphics = PicoGraphics(DISPLAY)

width = CosmicUnicorn.WIDTH
height = CosmicUnicorn.HEIGHT


# function for drawing outlined text
def outline_text(text, x, y):
graphics.set_pen(graphics.create_pen(int(OUTLINE_COLOUR[0]), int(OUTLINE_COLOUR[1]), int(OUTLINE_COLOUR[2])))
graphics.text(text, x - 1, y - 1, -1, 1)
graphics.text(text, x, y - 1, -1, 1)
graphics.text(text, x + 1, y - 1, -1, 1)
graphics.text(text, x - 1, y, -1, 1)
graphics.text(text, x + 1, y, -1, 1)
graphics.text(text, x - 1, y + 1, -1, 1)
graphics.text(text, x, y + 1, -1, 1)
graphics.text(text, x + 1, y + 1, -1, 1)

graphics.set_pen(graphics.create_pen(int(MESSAGE_COLOUR[0]), int(MESSAGE_COLOUR[1]), int(MESSAGE_COLOUR[2])))
graphics.text(text, x, y, -1, 1)


def run():
# Setup wifi
network_manager = NetworkManager(WIFI_COUNTRY, status_handler=status_handler)

app.add_resource(text, '/update')

# Connect to Wifi network
asyncio.get_event_loop().run_until_complete(network_manager.client(WIFI_CONFIG.SSID, WIFI_CONFIG.PSK))
while (not network_manager.isconnected()):
time.sleep(0.1)


cu.set_brightness(0.5)

# Start wifi connection
run()


async def message_update():
global MESSAGE
last_time = time.ticks_ms()
STATE_PRE_SCROLL = 0
STATE_SCROLLING = 1
STATE_POST_SCROLL = 2

shift = 0
state = STATE_PRE_SCROLL

# set the font
graphics.set_font("bitmap8")

# calculate the message width so scrolling can happen
msg_width = graphics.measure_text(MESSAGE, 1)
while 1:

msg_width = graphics.measure_text(MESSAGE, 1)
time_ms = time.ticks_ms()

if cu.is_pressed(CosmicUnicorn.SWITCH_BRIGHTNESS_UP):
cu.adjust_brightness(+0.01)

if cu.is_pressed(CosmicUnicorn.SWITCH_BRIGHTNESS_DOWN):
cu.adjust_brightness(-0.01)

if state == STATE_PRE_SCROLL and time_ms - last_time > HOLD_TIME * 1000:
if msg_width + PADDING * 2 >= width:
state = STATE_SCROLLING
last_time = time_ms

if state == STATE_SCROLLING and time_ms - last_time > STEP_TIME * 1000:
shift += 1
if shift >= (msg_width + PADDING * 2) - width - 1:
state = STATE_POST_SCROLL
last_time = time_ms

if state == STATE_POST_SCROLL and time_ms - last_time > HOLD_TIME * 1000:
state = STATE_PRE_SCROLL
shift = 0
last_time = time_ms

graphics.set_pen(graphics.create_pen(int(BACKGROUND_COLOUR[0]), int(BACKGROUND_COLOUR[1]), int(BACKGROUND_COLOUR[2])))
graphics.clear()

outline_text(MESSAGE, x=PADDING - shift, y=11)

# update the display
cu.update(graphics)

# pause for a moment (important or the USB serial device will fail)
await asyncio.sleep(0.001)


# The following is required to run both the web server and the scrolling text coherently
app._server_coro = app._tcp_server(host, port, app.backlog)
loop = asyncio.get_event_loop()
t1 = loop.create_task(message_update())
t2 = loop.create_task(app._server_coro)
loop.run_forever()
Loading