Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import network
- import urequests
- import time
- import socket
- import machine
- from machine import Pin
- from picozero import pico_led
- # You will need to first install kobo-wifi-remote on your kobo before this will work, https://github.com/sublipri/kobo-wifi-remote
- class Koboturner:
- # Initialize the device and network
- def __init__(self, ssid, password):
- self.ssid = ssid
- self.password = password
- self.url = "http://192.168.4"
- self.full_url = ""
- self.urlfound = False
- self.rbutton = Pin(16, Pin.IN) #, Pin.PULL_UP) if using buttons, add pull_up resistor
- self.lbutton = Pin(15, Pin.IN) #, Pin.PULL_UP) and change l/rbutton values to 0 in turn()
- self.ap_mode() # Initialize AP mode
- # Flashes the LED 'i' times.
- def led_flash(self, i):
- for x in range(i):
- print("flash")
- pico_led.on()
- time.sleep(0.1)
- pico_led.off()
- time.sleep(0.1)
- # Activates AP mode and sets up the device.
- def ap_mode(self):
- ap = network.WLAN(network.AP_IF)
- ap.config(essid=self.ssid, password=self.password)
- ap.active(True)
- while not ap.active():
- pass
- print('AP Mode Is Active, You can Now Connect')
- print('IP Address To Connect to:: ' + ap.ifconfig()[0])
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.bind(('', 80))
- s.listen(5)
- self.led_flash(2)
- def reqloop(self, lower, upper, lr):
- for i in range(lower, upper):
- self.full_url = f"{self.url}.{i}"
- print(self.full_url)
- try:
- response = urequests.get(f"{self.full_url}/{lr}", timeout=0.1) # Make HTTP GET request
- print("URL Response:", response.status_code)
- response.close()
- if response.status_code == 200:
- self.urlfound = True
- return True
- except Exception as e:
- print(f"Failed to connect to {self.url}: {e}")
- self.led_flash(1)
- # Loops through possible IPs and sends a request to find the right one.
- def getreqloop(self, lr):
- print(f"{lr} button pressed")
- self.led_flash(1)
- if self.urlfound:
- response = urequests.get(f"{self.full_url}/{lr}") # Make HTTP GET request
- print("URL Response:", response.status_code)
- response.close()
- else:
- if self.reqloop(16, 18, lr): # Devices seem to generally connect as 192.168.4.16 or .17, and the pico is .1
- return
- else:
- time.sleep(2)
- self.reqloop(2, 30, lr) # Expand search if initial loop fails, theoretically could go to 255
- self.led_flash(2)
- time.sleep(0.2)
- # Handles the right and left button presses.
- def turn(self):
- while True:
- try:
- # Handle the right button press
- if self.rbutton.value() == 1:
- self.getreqloop("right")
- # Handle the left button press
- if self.lbutton.value() == 1:
- self.getreqloop("left")
- except Exception as e:
- # Catch all exceptions and print the traceback
- print("Error in turn() function:", str(e))
- # Main execution
- koboturner = Koboturner('koboturner', '12345678')
- koboturner.turn()
Add Comment
Please, Sign In to add comment