added in the wifi examples from another branch

cosmic-wifi-mp-examples
Gee Bartlett 2023-02-22 17:06:41 +00:00 zatwierdzone przez Gee Bartlett
rodzic d4bb43a537
commit 4bc002091e
26 zmienionych plików z 2189 dodań i 0 usunięć

Wyświetl plik

@ -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)

Wyświetl plik

@ -0,0 +1,209 @@
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
'''
Display scrolling wisdom, quotes or greetz.
You can adjust the brightness with LUX + and -.
'''
# 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)
try:
from tinyweb.server import webserver
except ImportError:
# WIFI settings
WIFI_COUNTRY = "GB" # Changeme!
network_manager = NetworkManager(WIFI_COUNTRY, status_handler=status_handler)
uasyncio.get_event_loop().run_until_complete(network_manager.client(WIFI_CONFIG.SSID, WIFI_CONFIG.PSK))
# Install missing module
import upip
upip.install('logging')
from tinyweb.server import webserver
# 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 folloing is required to run both the web server and the scrolling text coherantly
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()

Wyświetl plik

@ -0,0 +1,102 @@
<http>
<head>
<style>
h1 {
align-content: center;
color: rgb(192, 192, 214);
margin-left: 20px;
background-color: darkmagenta;
font-size: xxx-large;
}
</style>
<script>
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host;
var displayText;
var colourBF ="#000000";
var colourFG ="#000000";
function convertHexToRgb(hex) {
// Convert the first 2 characters to hexadecimal
var r = parseInt(hex.substring(1, 3), 16),
// Convert the middle 2 characters to hexadecimal
g = parseInt(hex.substring(3, 5), 16),
// Convert the last 2 characters to hexadecimal
b = parseInt(hex.substring(5, 7), 16);
// append them all
return r + ", " + g + ", "
+ b ;
}
function updateCU(comm,val){
console.log(typeof(comm))
console.log(typeof(val))
console.log(comm, val)
fetch(baseUrl+"/update" + "?"+comm+"="+String(val))
.then(response => {
// indicates whether the response is successful (status code 200-299) or not
if (!response.ok) {
throw new Error(`Request failed with status ${reponse.status}`)
}
return response.json()
})
.then(data => {
console.log(data)
})
.catch(error => console.log(error))
}
function updateText(){
displayText = document.getElementById("inputtxt").value;
colourFG = convertHexToRgb(document.getElementById("inputfgcolour").value);
colourBG = convertHexToRgb(document.getElementById("inputbgcolour").value);
updateCU("colourfg", colourFG);
updateCU("text", displayText);
updateCU("colourbg", colourBG);
}
function updateColour(){
colourFG = document.getElementById('inputfgcolour').value;
colourBG = document.getElementById('inputbgcolour').value;
}
</script>
</head>
<body>
<h1 id="title">Cosmic Unicorn Web Text</h1>
<center>
<label for="inputtxt"> Enter text to display:</label>
<br>
<input type="text" id="inputtxt" name="inputtxt" required
minlength="4" size="16">
<br>
<label for="inputfgcolour"> Text Colour:</label>
<br>
<input type="color" id="inputfgcolour" name="inputfgcolour" required
minlength="4" maxlength="30" size="16" onchange="updateColour()" value='#000000'>
<br>
<label for="inputbgcolour"> Background Colour:</label>
<br>
<input type="color" id="inputbgcolour" name="inputbgcolour" required
minlength="4" maxlength="30" size="16" onchange="updateColour()" value='#000000'>
<br>
<button class="favorite styled"
onclick="updateText()"
type="button">
Update
</button>
<p>
Please type in what you wish to be displayed on the Cosmic Unicorn and whe you are ready hit update to update the display
</p>
</center>
</body>
</http>

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.5 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.6 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.6 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.0 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.0 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.0 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.2 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.3 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.7 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.8 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.7 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.2 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.2 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 2.1 KiB

Plik diff jest za duży Load Diff

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 81 KiB

Wyświetl plik

@ -0,0 +1,153 @@
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 urequests
import jpegdec
# Set your latitude/longitude here (find yours by right clicking in Google Maps!)
LAT = 53.38609085276884
LNG = -1.4239983439328177
TIMEZONE = "auto" # determines time zone from lat/long
URL = "http://api.open-meteo.com/v1/forecast?latitude=" + str(LAT) + "&longitude=" + str(LNG) + "&current_weather=true&timezone=" + TIMEZONE
WEATHER_TEXT = ''
user_icon = None
def get_data():
global WEATHER_TEXT, temperature, weathercode
print(f"Requesting URL: {URL}")
r = urequests.get(URL)
# open the json data
j = r.json()
print("Data obtained!")
print(j)
# parse relevant data from JSON
current = j["current_weather"]
temperature = current["temperature"]
windspeed = current["windspeed"]
winddirection = calculate_bearing(current["winddirection"])
weathercode = current["weathercode"]
date, now = current["time"].split("T")
WEATHER_TEXT = f"Temp: {temperature}°C Wind Speed: {windspeed}kmph Wind Direction: {winddirection} As of: {date}, {now}"
print(WEATHER_TEXT)
r.close()
def calculate_bearing(d):
# calculates a compass direction from the wind direction in degrees
dirs = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
ix = round(d / (360. / len(dirs)))
return dirs[ix % len(dirs)]
def status_handler(mode, status, ip):
global MESSAGE
print("Network: {}".format(WIFI_CONFIG.SSID))
# create galactic object and graphics surface for drawing
cu = CosmicUnicorn()
display = PicoGraphics(DISPLAY)
WIDTH = CosmicUnicorn.WIDTH
HEIGHT = CosmicUnicorn.HEIGHT
jpeg = jpegdec.JPEG(display)
TEXT_COLOUR = display.create_pen(200, 0, 200)
BLACK = display.create_pen(0, 0, 0)
WHITE = display.create_pen(255, 255, 255)
def run():
# Setup wifi
network_manager = NetworkManager(WIFI_CONFIG.COUNTRY, status_handler=status_handler)
# 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(1)
run() # Sets up Wifi connection
def outline_text(text, x, y):
display.set_pen(BLACK)
display.text(text, x - 1, y - 1, -1, 1)
display.text(text, x, y - 1, -1, 1)
display.text(text, x + 1, y - 1, -1, 1)
display.text(text, x - 1, y, -1, 1)
display.text(text, x + 1, y, -1, 1)
display.text(text, x - 1, y + 1, -1, 1)
display.text(text, x, y + 1, -1, 1)
display.text(text, x + 1, y + 1, -1, 1)
display.set_pen(WHITE)
display.text(text, x, y, -1, 1)
def draw_page(cycle):
global user_icon
text_cycle = cycle % 1000
cycle = cycle % 4
# Clear the display
display.set_pen(15)
display.clear()
# Draw the page header
display.set_font("bitmap6")
if temperature is not None:
# Choose an appropriate icon based on the weather code
# Weather codes from https://open-meteo.com/en/docs
if user_icon is not None:
icons = ["icons/snow{0}.jpg".format(cycle + 1), "icons/rain{0}.jpg".format(cycle + 1), "icons/cloud{0}.jpg".format(cycle + 1), "icons/sun{0}.jpg".format(cycle + 1), "icons/storm{0}.jpg".format(cycle + 1)]
jpeg.open_file(icons[user_icon])
else:
if weathercode in [71, 73, 75, 77, 85, 86]: # codes for snow
jpeg.open_file("icons/snow{0}.jpg".format(cycle + 1))
elif weathercode in [51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82]: # codes for rain
jpeg.open_file("icons/rain{0}.jpg".format(cycle + 1))
elif weathercode in [1, 2, 3, 45, 48]: # codes for cloud
jpeg.open_file("icons/cloud{0}.jpg".format(cycle + 1))
elif weathercode in [0]: # codes for sun
jpeg.open_file("icons/sun{0}.jpg".format(cycle + 1))
elif weathercode in [95, 96, 99]: # codes for storm
jpeg.open_file("icons/storm{0}.jpg".format(cycle + 1))
jpeg.decode(0, 0, jpegdec.JPEG_SCALE_FULL)
display.set_pen(TEXT_COLOUR)
outline_text(WEATHER_TEXT, 32 - text_cycle, 0)
else:
display.set_pen(0)
display.set_pen(15)
display.text("Unable to display weather! Check your network settings in WIFI_CONFIG.py", 5, 65, WIDTH, 1)
cu.update(display)
while 1:
get_data()
for count in range(500):
if cu.is_pressed(CosmicUnicorn.SWITCH_A):
user_icon = 0
if cu.is_pressed(CosmicUnicorn.SWITCH_B):
user_icon = 1
if cu.is_pressed(CosmicUnicorn.SWITCH_C):
user_icon = 2
if cu.is_pressed(CosmicUnicorn.SWITCH_D):
user_icon = 3
if cu.is_pressed(CosmicUnicorn.SWITCH_BRIGHTNESS_UP):
user_icon = 4
if cu.is_pressed(CosmicUnicorn.SWITCH_BRIGHTNESS_DOWN):
user_icon = None
draw_page(count)
time.sleep(0.2)