﻿import socket #last file is main.py and run off battery
import time
import network
#import secrets


import machine


from machine import Pin,I2C
from ssd1306 import SSD1306_I2C


redLEDPin=16
greenLEDPin=17
blueLEDPin=18


redLED=Pin(redLEDPin,Pin.OUT)
greenLED=Pin(greenLEDPin,Pin.OUT)
blueLED=Pin(blueLEDPin,Pin.OUT)
redLED.value(0)
greenLED.value(0)
blueLED.value(0) #test1
i2c = I2C(0,sda=Pin(0),scl=Pin(1),freq=400000)
dsp= SSD1306_I2C(128,64,i2c)
#dsp.text('Hello World',0,0)
#dsp.show()   #test2


wifi=network.WLAN(network.STA_IF)
time.sleep(.5)
wifi.active(True)
time.sleep(.5)
wifi.connect('CompEngDpcdsb','CompEng2023!')
##wifi.connect(secrets.SSID,secrets.PASSWORD)
cnt=0
while wifi.isconnected()==False:
    print('Waiting . . .')
    dsp.text('. . . Waiting',0,0)
    dsp.text(str(cnt),0,16)
    dsp.show()
    time.sleep(1)
    cnt=cnt+1
    dsp.fill(0) #sometimes unplug & replug pico
dsp.fill(0)
wifiInfo=wifi.ifconfig()
ServerIP=wifiInfo[0] #test   print(wifiInfo)
ServerPort=2222
bufferSize=1024
UDPServer=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPServer.bind((ServerIP,ServerPort))
dsp.text(str(ServerIP),0,0) #IP:
dsp.text('PORT: '+str(ServerPort),0,16)
dsp.show()  #test


while True:
    dsp.text(str(ServerIP),0,0) #IP:
    dsp.text('PORT: '+str(ServerPort),0,16)
    cmd,address=UDPServer.recvfrom(bufferSize)
    cmdDecoded=cmd.decode('utf-8')
    print(cmdDecoded)
    dsp.text('Message RECEIVED: ',0,26)
    dsp.text(str(cmdDecoded),16,36)
    dsp.text('From:',0,46)
    dsp.text(str(address[0]),16,56)
    dsp.show()
    dsp.fill(0) #clear screen
    dataString='Received Your Command: '+cmdDecoded
    dataStringEncoded=dataString.encode('utf-8')
    UDPServer.sendto(dataStringEncoded,address)
    if cmdDecoded.lower()=='red':
        redLED.value(1)
        greenLED.value(0)
        blueLED.value(0)
    elif cmdDecoded.lower()=='green':
        redLED.value(0)
        greenLED.value(1)
        blueLED.value(0)
    elif cmdDecoded.lower()=='blue':
        redLED.value(0)
        greenLED.value(0)
        blueLED.value(1)
    time.sleep(1)