class wifi_module(object):
    def __init__(self):
        self.ui = PiUi()

    def on_submit_click(self):
        self.page = self.ui.new_ui_page(title="login succesful")

    def login_page(self):
        self.page = self.ui.new_ui_page(title="Login and Password",
                                        prev_text="Back",
                                        onprevclick=main_menu)
        login = self.page.add_textbox('username', "h1")
        password = self.page.add_input("password", "password")
        button = self.page.add_button("Submit", on_submit_click)

    def getssid(self):
        command = "./getESSID"
        process = subprocess.check_output(command, shell=True)
        namelist = process.split('\n')
        for i in namelist:
            #print i
            if i not in noduplist and i != '':
                noduplist.append(i)
        print noduplist
        self.page = self.ui.new_ui_page(title="Wifi Login")
        list1 = self.page.add_list()
        print list1
        for i in noduplist:
            list1.add_item(i, onclick=self.login_page, chevron=True)
        self.ui.done()
Example #2
0
    def __init__(self):
        self.page = None
        self.title = None
        self.txt = None
        self.status_head = None
        self.status_title = None
        self.status_txt = None
        self.action_txt = None
        self.download_title = None
        self.download_link = None
        self.img = None
        self.ui = PiUi()
        self.src = None
        self.rfstatus = RFStatusCheck.RFStatusCheck()

        self.status_states = {
            0 : '<p style=\"color:SlateGray;font-style:italic;\">Checking Status...</p>',
            1 : '<p style=\"color:blue;font-weight:normal;\">Waiting to scan inventory.</p>',
            2 : '<p style=\"color:LimeGreen;font-weight:bold;\">Inventory scan in progress.</p>',
            3 : '<p style=\"color:blue;font-weight:bold;\">Inventory scan completed successfully.</p>',
            4 : '<p style=\"color:red;font-weight:bold;\">Inventory scan failed.</p>'
        }

        self.action_states = {
            0 : '<p>&nbsp;</p>',
            1 : '<p style=\"color:SlateGray;font-style:italic;\">Starting Data Collection...</p>',
            2 : '<p style=\"color:DarkSlateGray;font-weight:normal;\">Inventory scan is already running.</p>',
            3 : '<p style=\"color:SlateGray;font-style:italic;\">Stopping Data Collection...</p>',
            4 : '<p style=\"color:DarkSlateGray;font-weight:normal;\">Inventory scan is not running.</p>'
        }
        self.status_state = 0
        self.action_state = 0
Example #3
0
 def __init__(self):
     self.title = None
     self.txt = None
     self.img = None
     self.img_dir = os.path.join(current_dir, 'imgs')
     self.thumbs_dir = os.path.join(current_dir, 'thumbs')
     self.ui = PiUi(self.thumbs_dir)
     self.src = "sunset.png"
 def __init__(self, queuey, receiveQueuey):
     self.title = None
     self.txt = None
     self.img = None
     self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
     self.src = "sunset.png"
     self.queuey = queuey  #ADDED FOR WIFI - queue to hold the outgoing messages, connecting the piui and wifi program threads
     self.receiveQueuey = receiveQueuey
     self.piuiLightDict = {
     }  #this dict will store the active lights' lightModulePiUiInfo; keys are the port numbers
     self.currentPage = None
     self.titles = {
     }  #this is a dictionary that is used by the toggle page to remember the title for each light; keys are the port numbers
     self.nameInputs = {
     }  #this is a dictionary that is used by the toggle page to remember the name textbox for each light; keys are port numbers
Example #5
0
 def __init__(self):
     self.title = None
     self.txt = None
     self.img = None
     self.img_dir=os.path.join(current_dir, 'imgs')
     self.thumbs_dir=os.path.join(current_dir, 'thumbs')
     self.ui = PiUi(self.thumbs_dir)
     self.src = "sunset.png"
Example #6
0
class LumoUi:
    def __init__(self):
        self.title = None
        self.txt = None
        self.ui = PiUi()
        self.pattern = None

    def page_menu(self):
        self.page = self.ui.new_ui_page(title="LUMO Smart Lamp")
        self.list = self.page.add_list()
        self.list.add_item("Combo", chevron=True, onclick=self.page_patterns)
        self.list.add_item("Mode", chevron=True, onclick=self.page_modes)
        self.list.add_item("Turn Off",
                           chevron=False,
                           onclick=partial(self.uMode, "off"))
        self.ui.done()

    def page_modes(self):
        self.page = self.ui.new_ui_page(title="Mode")
        self.list = self.page.add_list()
        for mode in _modes.keys().sort():
            self.list.add_item(mode,
                               chevron=False,
                               onclick=partial(self.uMode, mode))

    def page_patterns(self):
        self.page = self.ui.new_ui_page(title="Pattern")
        self.list = self.page.add_list()
        for pattern in _patterns.keys().sort():
            self.list.add_item(pattern,
                               chevron=True,
                               onclick=partial(self.uPattern, pattern))

    def page_colors(self):
        self.page = self.ui.new_ui_page(title="Color")
        self.list = self.page.add_list()
        for color in _colors.keys().sort():
            self.list.add_item(color,
                               chevron=False,
                               onclick=partial(self.uColor, color))

    def uMode(self, c):
        goMode(c)
        self.page_menu()

    def uPattern(self, c):
        self.pattern = c
        self.page_colors()

    def uColor(self, c):
        goCombo(self.pattern, c)
        self.page_menu()

    def main(self):
        self.menu_page()
        self.ui.done()
def getssid():

    command = "nmcli -t -f ssid dev wifi| cut -d\\' -f2"
    process = subprocess.check_output(
        "nmcli -t -f ssid dev wifi| cut -d\\' -f2", shell=True)
    namelist = process.split('\n')
    noduplist = []
    for i in namelist:
        if i not in noduplist:
            noduplist.append(i)
    print(noduplist)

    ui = PiUi()
    page = ui.new_ui_page(title="Available Networks")
    page_form = ui.new_ui_page(title="Enter Login Details")
    txt = page_form.add_input("text", "loginID")
    txt2 = page_form.add_input("text", "password")
    button = page.add_button("submit", onButtonClick)
    list = page.addlist()
    for i in nonduplist:
        list.add_item(nonduplist[i], onclick=page_form)
Example #8
0
class CatFeeder(object):

    def __init__(self):
        self.servo = Servo()
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))

    def main(self):
        self.main_menu()
        self.ui.done()

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="Cat Feeder")
        self.page.add_element("hr")
        self.list = self.page.add_list()
        self.list.add_item("Nourrir", chevron=True, onclick=self.page_control)
        self.list.add_item("Journal", chevron=True, onclick=self.page_feed_logs)
        self.ui.done()

    def page_control(self):
        self.page = self.ui.new_ui_page(title="Nourrir", prev_text="<", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Control", "h1")
        plus = self.page.add_button("Ouvrir la trap", self.onupclick)
        minus = self.page.add_button("Fermer la trap", self.ondownclick)

    def page_feed_logs(self):
        self.page.add_textbox("Journal", "h1")
        self.page.add_element("hr")
        con = lite.connect('catfeeder.db')
        with con:
            
            cur = con.cursor()    
            cur.execute("SELECT * FROM feedLogs")

            rows = cur.fetchall()

            for row in rows:
                self.page.add_textbox(row, "p")

    def onupclick(self):
        self.title.set_text("Ouvert ")
        self.servo.servo_CW(1200)

    def ondownclick(self):
        self.title.set_text("Ferme ")
        self.servo.servo_CCW(2000)
Example #9
0
class RemoteSkyUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"

    def take_photo(self):
        self.page = self.ui.new_ui_page(title="Take Photo", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("No photo", "h1")
        self.img = self.page.add_image("sunset.png")
        plus = self.page.add_button("Take Photo", self.ontakephoto)

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="RemoteSky Control Panel")
        self.list = self.page.add_list()
        self.list.add_item("Take Photo", chevron=True, onclick=self.take_photo)
        self.ui.done()

    def main(self):
        self.main_menu()
        self.ui.done()

    def ontakephoto(self):
        photos = self.capturePhoto()
        self.title.set_text("Photo taken")
        self.img.set_src(photos['thumb'])

    def capturePhoto(self):
        data = {}
        sock = socket.create_connection(('localhost', 5555))
        try:
            data['photo'] = sock.recv(10000)
            data['thumb'] = sock.recv(10000)
        finally:
            sock.close()

        return data
Example #10
0
 def __init__(self):
     self.servo = Servo()
     self.title = None
     self.txt = None
     self.img = None
     self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
class DemoPiUi(object):
    def __init__(self, queuey, receiveQueuey):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"
        self.queuey = queuey  #ADDED FOR WIFI - queue to hold the outgoing messages, connecting the piui and wifi program threads
        self.receiveQueuey = receiveQueuey
        self.piuiLightDict = {
        }  #this dict will store the active lights' lightModulePiUiInfo; keys are the port numbers
        self.currentPage = None
        self.titles = {
        }  #this is a dictionary that is used by the toggle page to remember the title for each light; keys are the port numbers
        self.nameInputs = {
        }  #this is a dictionary that is used by the toggle page to remember the name textbox for each light; keys are port numbers

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project",
                              "h1")
        self.page.add_element("hr")
        self.page.add_textbox(
            "You can use any static HTML element " +
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.",
            "p")
        self.page.add_element("hr")
        self.page.add_textbox(
            "Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 5):
            update.set_text(str(a))
            time.sleep(1)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.img = self.page.add_image("sunset.png")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_lightController(self):
        self.currentPage = "page_lightController"  #still need to test to make sure this actually sets the variable correctly when loading a page

        self.page = self.ui.new_ui_page(title="Light Control",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.titles = {}  # A dictionary that stores the textboxes on the page
        self.nameInputs = {}
        for port in self.piuiLightDict:
            self.titles[port] = self.page.add_textbox(
                "Light name: " + self.piuiLightDict[port].name + "\nPort: " +
                str(port) + "\nStatus: " + self.piuiLightDict[port].state,
                "h2")
            self.nameInputs[port] = self.page.add_input(
                "text", "Change Nickname")
            self.page.add_button("Save Nickname",
                                 functools.partial(self.onLightNameType, port))
            self.page.add_button(
                "Change State",
                functools.partial(self.onLightControlClick, port))
            self.page.add_button(
                "Reset Time", functools.partial(self.onTimerResetClick, port))
        while True:
            incomingSignal = self.lightReceiveEvent()
            if incomingSignal is not None:  #if there is a message coming from the wifi, process it
                self.processSignal(incomingSignal)

    def processSignal(self, incomingSignal):
        signal = incomingSignal.split(":")[1]
        port = int(incomingSignal.split(":")[0])
        if signal == "CONNECTED":
            self.piuiLightDict[port] = lightModulePiUiInfo(
                port)  #add a new light module to the piui light dictionary
            self.lightCommandEvent(
                str(port) + ":" + "GETSTATE_COMMAND"
            )  #get the current state of the light the just connected
            self.lightCommandEvent(
                str(port) + ":" + "GETNAME"
            )  #get the current state of the light the just connected
            if self.currentPage == "page_lightController":
                self.titles[port] = self.page.add_textbox(
                    "Light name: " + self.piuiLightDict[port].name +
                    "\nPort: " + str(port) + "\nStatus: " +
                    self.piuiLightDict[port].state, "h2")
                self.nameInputs[port] = self.page.add_input(
                    "text", "Change Nickname")
                self.page.add_button(
                    "Save Nickname",
                    functools.partial(self.onLightNameType, port))
                self.page.add_button(
                    "Change State",
                    functools.partial(self.onLightControlClick, port))
                self.page.add_button(
                    "Reset Time",
                    functools.partial(self.onTimerResetClick, port))
        elif signal == "ON" or signal == "CON_ON":
            self.piuiLightDict[port].state = "ON"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif signal == "OFF" or signal == "CON_OFF":
            self.piuiLightDict[port].state = "OFF"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif signal == "CLOSED":
            self.piuiLightDict.pop(
                port, None
            )  #if the light has become offline, take it out of the dictionary
            if self.currentPage == "page_lightController":
                self.page_lightController(
                )  #reset the page_toggles page if a light has been taken out of the list
        elif signal == "STATEIS_ON":  #this is a reply to the request to get the current state of the light
            self.piuiLightDict[port].state = "ON"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif signal == "STATEIS_OFF":  #this is a reply to the request to get the current state of the light
            self.piuiLightDict[port].state = "OFF"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif isinstance(signal, str) and len(signal) > 6 and signal[
                0:
                7] == "NAMEIS_":  #this is a reply to the request to get the current name of the light
            self.piuiLightDict[port].name = signal[7:]
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif isinstance(
                signal,
                str) and len(signal) > 11 and signal[0:12] == "NAMECHANGED_":
            self.piuiLightDict[port].name = signal[12:]
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif signal == "MOTIONTRIGGERED":  #the motion sensors have been triggered, turning the light off
            self.piuiLightDict[port].state = "OFF - MOTION"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)
        elif signal == "TIMERTRIGGERED":  #the timer has run out, turning the light off
            self.piuiLightDict[port].state = "OFF - TIMER DONE"
            if self.currentPage == "page_lightController":
                self.changeLightText(port)

    '''
    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")
    '''

    def main_menu(self):
        self.currentPage = "main_menu"  #SHOULD TEST IF THIS ACTUYALLY CHANGES WHEN GOING BACK TO MAIN<<<<<<<<<<<<<<<<<<<<
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content",
                           chevron=True,
                           onclick=self.page_static)
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Light Control",
                           chevron=True,
                           onclick=self.page_lightController)
        #self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        while True:
            incomingSignal = self.lightReceiveEvent()
            if incomingSignal is not None:
                self.processSignal(incomingSignal)

        self.ui.done()

    def main(self):
        self.main_menu()
        self.ui.done()
        print("THREE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")

    def onupclick(self):
        self.title.set_text("Up ")
        #self.queuey.put("yo")#THIS LINE IS AN EXAMPLE OF SENDING A MESSAGE TO THE WIFI THREAD OF THE PROGRAM###########
        print("Up")

    def ondownclick(self):
        self.title.set_text("Down")
        print("Down")

    def onhelloclick(self):
        print("onstartclick")
        self.title.set_text("Hello " + self.txt.get_text())
        print("Start")

    def onpicclick(self):
        if self.src == "sunset.png":
            self.img.set_src("sunset2.png")
            self.src = "sunset2.png"
        else:
            self.img.set_src("sunset.png")
            self.src = "sunset.png"

    def onLightControlClick(self, port):
        value = "CHANGESTATE_COMMAND"
        self.piuiLightDict[port].state = "CHANGING_STATE"
        self.lightCommandEvent(str(port) + ":" + value)
        self.changeLightText(port)

    def onLightNameType(self, port):
        newName = self.nameInputs[port].get_text()
        value = "CHANGENAME_" + newName
        self.piuiLightDict[port].name = "name_changing"
        self.lightCommandEvent(str(port) + ":" + value)
        self.changeLightText(port)

    def onTimerResetClick(self, port):
        value = "RESETTIMER"
        self.lightCommandEvent(str(port) + ":" + value)

    def changeLightText(self, port):
        #index = self.indices[str(port)]
        self.titles[port].set_text("Light name: " +
                                   self.piuiLightDict[port].name + "\nPort: " +
                                   str(port) + "\nStatus: " +
                                   self.piuiLightDict[port].state)

#AN EXAMPLE OF A POTENTIAL FUNCTION THAT COULD BE USED FOR
#SENDING WIFI MESSAGES FROM PIUI################

    def lightCommandEvent(self, command):
        self.queuey.put(command)

    def lightReceiveEvent(self):
        if not self.receiveQueuey.empty():
            return self.receiveQueuey.get()
        else:
            return None
Example #12
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content", prev_text="Back",
            onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project", "h1")
        self.page.add_element("hr")
        self.page.add_textbox("You can use any static HTML element " + 
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.", "p")
        self.page.add_element("hr")
        self.page.add_textbox("Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 10):
            update.set_text(str(a))
            time.sleep(1)


    def page_smalltalk(self):
        self.page = self.ui.new_ui_page(title="Small Talk", prev_text="Back", onprevclick=self.main_menu)

        self.title = self.page.add_textbox("Small Talk Questions", "h1")
        bq1 = self.page.add_button("HowAreYou", self.q1)
        bq2 = self.page.add_button("TellMe", self.q2)
        bq3 = self.page.add_button("Brothers/Sisters", self.q3)
        bq4 = self.page.add_button("Pets", self.q4)
        bq5 = self.page.add_button("Birthday", self.q5)
        bq6 = self.page.add_button("Grade", self.q6)
        bq7 = self.page.add_button("Breakfast", self.q7)
        bq8 = self.page.add_button("School", self.q8)
        self.title = self.page.add_textbox("Small Talk Answers", "h1")
        b1 = self.page.add_button("ImGood", self.a1)
        b2 = self.page.add_button("ImOkay", self.a2)
        b3 = self.page.add_button("NotGreat", self.a3)
        b4 = self.page.add_button("AboutMe", self.a4)
        b5 = self.page.add_button("Brothers/Sisters", self.a5)
        b6 = self.page.add_button("Pets", self.a6)
        b7 = self.page.add_button("Birthday", self.a7)
        b8 = self.page.add_button("Grade", self.a8)
        b9 = self.page.add_button("Breakfast", self.a9)
        b10 = self.page.add_button("School", self.a10)
        self.title = self.page.add_textbox("Output String", "h1")

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images", prev_text="Back", onprevclick=self.main_menu)
        self.img = self.page.add_image("sunset.png")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles", prev_text="Back", onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")
        

    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Small Talk", chevron=True, onclick=self.page_smalltalk)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()


    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def a1(self):
        self.title.set_text("I'm good")
        print "I'm good"

    def a2(self):
        self.title.set_text("I'm okay")
        print "I'm okay"

    def a3(self):
        self.title.set_text("Not great. I'm having trouble figuring out some math problems I was assigned")
        print "Not great.  I'm having trouble figuring out some math problems I was assigned"

    def a4(self):
        self.title.set_text("Well, I love reading and watching TV.  I can't do everything humans can do because I'm a robot, but I love playing wit humans like you!")
        print "Well, I love reading and watching TV.  I can't do everything humans can do because I'm a robot, but I love playing wit humans like you!"

    def a5(self):
        self.title.set_text("Robots don't really have brothers and sisters, but there are others like me out there! I like to think of them as my brothers and sisters.")
        print "Robots don't really have brothers and sisters, but there are others like me out there! I like to think of them as my brothers and sisters."

    def a6(self):
        self.title.set_text("I wish! I think dogs are really fun.")
        print "I wish! I think dogs are really fun."

    def a7(self):
        self.title.set_text("I was created on May 15")
        print "I was created on May 15"

    def a8(self):
        self.title.set_text("Robots can go to school with kids from all different grades, but I'm eight!")
        print "Robots can go to school with kids from all different grades, but I'm eight!"

    def a9(self):
        self.title.set_text("I didn't have breakfast today, but I love doughnuts!")
        print "I didn't have breakfast today, but I love doughnuts!"

    def a10(self):
        self.title.set_text("Today, I learned about the sea.  Did you know that a shark is the only known fish that can blink with both eyes?")
        print "Today, I learned about the sea.  Did you know that a shark is the only known fish that can blink with both eyes?"

    def q1(self):
        self.title.set_text("How are you")
        print "How are you"

    def q2(self):
        self.title.set_text("Tell me about yourself")
        print "Tell me about yourself"

    def q3(self):
        self.title.set_text("Do you have any brothers or sisters?")
        print "Do you have any brothers or sisters?"

    def q4(self):
        self.title.set_text("Do you have any pets")
        print "Do you have any pets"

    def q5(self):
        self.title.set_text("When is your birthday?")
        print "When is your birthday?"

    def q6(self):
        self.title.set_text("What grade are you in?")
        print "What grade are you in?"

    def q7(self):
        self.title.set_text("What did you have for breakfast today?")
        print "What did you have for breakfast today?"

    def q8(self):
        self.title.set_text("What did you do in school today?")
        print "What did you do in school today?"
        

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"

    def onhelloclick(self):
        print "onstartclick"
        self.title.set_text("Hello " + self.txt.get_text())
        print "Start"

    def onpicclick(self):
        if self.src == "sunset.png":
          self.img.set_src("sunset2.png")
          self.src = "sunset2.png"
        else:
          self.img.set_src("sunset.png")
          self.src = "sunset.png"

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))
Example #13
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.img_dir=os.path.join(current_dir, 'imgs')
        self.thumbs_dir=os.path.join(current_dir, 'thumbs')
        self.ui = PiUi(self.thumbs_dir)
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content", prev_text="Back",
            onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project", "h1")
        self.page.add_element("hr")
        self.page.add_textbox("You can use any static HTML element " + 
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.", "p")
        self.page.add_element("hr")
        self.page.add_textbox("Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 5):
            update.set_text(str(a))
            time.sleep(1)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images", prev_text="Back", onprevclick=self.main_menu)
        takepic = self.page.add_button("Take Picture", self.takepicbutton)
        self.capturetext = self.page.add_textbox("")
        self.page.add_element('br')
        for root, _, files in os.walk(self.thumbs_dir):
            for f in files:
                self.page.add_image(f)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles", prev_text="Back", onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")
        

    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content", chevron=True, onclick=self.page_static)
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()


    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"

    def onhelloclick(self):
        print "onstartclick"
        self.title.set_text("Hello " + self.txt.get_text())
        print "Start"

    def takepicbutton(self):
        self.capturetext.set_text("wait...")
        picname = time.strftime("%Y%m%d_%H%M%S", time.gmtime())
        os.system("raspistill -t 0 -o " + self.img_dir + "/" + picname + ".jpg")
        newPic = Image.open(self.img_dir + "/" + picname + ".jpg")
        newPreview = newPic.resize((280, 200), Image.NEAREST)
        newPreview.save(self.thumbs_dir + "/" + picname + ".jpg")
        self.capturetext.set_text("DONE")

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))
Example #14
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
       # self.src = "sunset.png"
    def main_menu(self):
        self.page = self.ui.new_ui_page(title="Controlul Masinii")
        self.title=self.page.add_textbox("Fata Spate", "h1")
        fwd=self.page.add_button("&uarr;", self.onupclick)
        bwd=self.page.add_button("&darr;", self.ondownclick)
	self.title2=self.page.add_textbox("Stanga dreapta", "h1")
	lft=self.page.add_button("&larr;", self.onleftclick)
	rht=self.page.add_button("&rarr;", self.onrightclick)
	self.page.add_textbox("Viteza: ", "h1")
	speed=self.page.add_textbox("%d m\s",%self.reads.a)
	self.page.add_textbox("Distanta: ","h1")
	dist=self.page.add_textbox("%d m",%self.readd.b)
	self.page.add_element("hr")
	stop=self.page.add_button("Stop", self.onstopclick)	
	self.ui.done()
	def main(self):
        self.main_menu()
        self.ui.done()

    def reads (self):
	a=call(["sudo python /home/piui/uart/reads.py &"],shell=true)
    
    def readd (self):
	b=call(["sudo python /home/piui/uart/readd.py &"],shell=true)

    def onupclick(self):
        self.title.set_text("Forward ")
        print "Forward"
	call(["sudo python /home/pi/piui/uart/fwd.py &"],shell=true)

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"
	call(["sudo python /home/pi/piui/uart/bwd.py &"],shell=true)

    def onleftclick(self):
	self.title2.set_text("left")
	call(["sudo python /home/pi/piui/uart/left.py &"],shell=true)

    def onrightclick(self):
	self.title2.set_text("right")
	call(["sudo python /home/pi/piui/uart/rght.py &"],shell=true)

    def onstopclick(self):
	self.title.set_text("Stop")
        call(["sudo python /home/pi/piui/uart/stop.py &"],shell=true)

def main():
  piui = DemoPiUi()
  piui.main()

if __name__ == '__main__':
    main()
#!usr/bin/env python
import time
import serial
ser=serial.Serial(
        port='/dev/ttyAMA0',
        baudrate=9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
)
counter=0
f="8"
while counter<3:
        ser.write(f)
        time.sleep(1)
        print f
        counter+=1
Example #15
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Logs and Statistics", prev_text="Back",
            onprevclick=self.main_menu)
        mainProcWrite("logs\n")
        self.title = self.page.add_textbox("Logs:", "h1")
        # self.page.add_element("hr")
        # self.page.add_textbox("You can use any static HTML element " + 
        #     "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.", "p")
        # self.page.add_element("hr")
        # self.page.add_textbox("Your python code can update page contents at any time.", "p")
        # update = self.page.add_textbox("Like this...", "h2")
        # logBox = self.page.add_textbox("2015-04-17 10:39:51 Temp=12.5*C Hum=55.7% Moist=False\n time"
        #    + "<br /> newline", "pre")
        logBox = self.page.add_textbox("Retreiving data", "pre")
        # sleep(2)
        for a in range(1, 4):
            # update.set_text(str(a))
            logBox.set_text("Retreiving data"+('.'*a))
            sleep(1)
        lines = []
        with open(os.path.join(current_dir,'logs'), 'r') as content_file:
        # with open(os.path.join(current_dir,'stgs2.py'), 'r') as content_file:
              lines.append(content_file.read())
        message = '\n'.join(lines)
	self.title.set_text("")
        logBox.set_text(message)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Commit changes", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("", "h1")
        # plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Commit &darr;", self.ondownclick)

    def page_lights(self):
        self.page = self.ui.new_ui_page(title="Lights setup", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("rPi time: "+strftime("%d-%X"), "h1")
        self.labelStart = self.page.add_textbox("Start [hour]: "+str(stgs.lightStart), "h2")
        self.txtStart = self.page.add_input("number", "new Start hour [0..23]")
        self.labelDuration = self.page.add_textbox("Duration [hour]: "+str(stgs.lightDuration), "h2")
        self.txtDuration = self.page.add_input("number", "new Duration hours [0..23]")
        button = self.page.add_button("Save", self.onlight)

    def page_treshold(self):
        self.page = self.ui.new_ui_page(title="Tresholds setup", prev_text="Back", onprevclick=self.main_menu)
        self.labelTemperature = self.page.add_textbox("Temperature [celsius]: "+str(stgs.temperature), "h2")
        self.txtTemperature = self.page.add_input("number", "new Temperature in celsius [0..100]")
        self.labelHumidity = self.page.add_textbox("Humidity [percentage]: "+str(stgs.humidity), "h2")
        self.txtHimidity = self.page.add_input("number", "new Humidity in percentage [0..100]")
        button = self.page.add_button("Save", self.ontreshold)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images", prev_text="Back", onprevclick=self.main_menu)
        self.img = self.page.add_image("sunset.png")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles", prev_text="Back", onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")
        

    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="Zelena Soba setup")
        self.list = self.page.add_list()
        self.list.add_item("Logs", chevron=True, onclick=self.page_static)
        self.list.add_item("Lights", chevron=True, onclick=self.page_lights)
        self.list.add_item("Treshold", chevron=True, onclick=self.page_treshold)
#        self.list.add_item("Pumps", chevron=True, onclick=self.page_lights)
        self.list.add_item("Commit", chevron=True, onclick=self.page_buttons)
#        self.list.add_item("Images", chevron=True, onclick=self.page_images)
#        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
#        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()


    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def ondownclick(self):
        stgs_file = open(os.path.join(current_dir, "stgs.py"), "w")
        stgs_file.write("class Class(): pass\n"
          + "stgs=Class()\n\n")
        stgs_file.write("stgs.temperature = %s\n" % stgs.temperature)
        mainProcWrite  ("stgs.temperature = %s\n" % stgs.temperature)
        stgs_file.write("stgs.humidity = %s\n" % stgs.humidity)
        mainProcWrite  ("stgs.humidity = %s\n" % stgs.humidity)
        stgs_file.write("stgs.pomp1duration = %s\n" % stgs.pomp1duration)
        mainProcWrite  ("stgs.pomp1duration = %s\n" % stgs.pomp1duration)
        stgs_file.write("stgs.pomp2duration = %s\n" % stgs.pomp2duration)
        mainProcWrite  ("stgs.pomp2duration = %s\n" % stgs.pomp2duration)
        stgs_file.write("stgs.lightStart = %s\n" % stgs.lightStart)
        mainProcWrite  ("stgs.lightStart = %s\n" % stgs.lightStart)
        stgs_file.write("stgs.lightDuration = %s\n" % stgs.lightDuration)
        mainProcWrite  ("stgs.lightDuration = %s\n" % stgs.lightDuration)
        stgs_file.close()
        self.title.set_text("Saved.. reload page!")
	sys.exit(1)

    def onlight(self):
        try:
          i = int(self.txtStart.get_text())
          if i>=0 and i<24: stgs.lightStart = i
          self.labelStart.set_text("Start [hour]: "+str(stgs.lightStart))
        except: None
        try:
          i = int(self.txtDuration.get_text())
          if i>=0 and i<24:  stgs.lightDuration = i
          self.labelDuration.set_text("Duration [hour]: "+str(stgs.lightDuration))
        except: None
        print "Start"

    def ontreshold(self):
        try:
          i = int(self.txtTemperature.get_text())
          if i>=0 and i<101: stgs.temperature = i
          self.labelTemperature.set_text("Temperature [celsius]: "+str(stgs.temperature))
        except: None
        try:
          i = int(self.txtHimidity.get_text())
          if i>=0 and i<101:  stgs.humidity = i
          self.labelHumidity.set_text("Humidity [percentage]: "+str(stgs.humidity))
        except: None
        print "Start"
Example #16
0
class DemoPiUi(object):
    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project",
                              "h1")
        self.page.add_element("hr")
        self.page.add_textbox(
            "You can use any static HTML element " +
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.",
            "p")
        self.page.add_element("hr")
        self.page.add_textbox(
            "Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 5):
            update.set_text(str(a))
            time.sleep(1)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.img = self.page.add_image("sunset.png")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle,
                                                      "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")

    def page_console(self):
        con = self.ui.console(title="Console",
                              prev_text="Back",
                              onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content",
                           chevron=True,
                           onclick=self.page_static)
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()

    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print("Up")

    def ondownclick(self):
        self.title.set_text("Down")
        print("Down")

    def onhelloclick(self):
        print("onstartclick")
        self.title.set_text("Hello " + self.txt.get_text())
        print("Start")

    def onpicclick(self):
        if self.src == "sunset.png":
            self.img.set_src("sunset2.png")
            self.src = "sunset2.png"
        else:
            self.img.set_src("sunset.png")
            self.src = "sunset.png"

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))
import os
import subprocess
from piui import PiUi
ui=PiUi()

noduplist = []

def on_submit_click():
  page=ui.new_ui_page(title="login succesful")

def login_page():
  page=ui.new_ui_page(title="Login and Password", prev_text="Back", onprevclick=main_menu)
  #page.add_textbox(i,"hr")
  password= page.add_input("password","password")
  page.add_button("Submit", on_submit_click)


def main_menu():
  page= ui.new_ui_page(title="Wifi Login")
  list= page.add_list()
  for i in noduplist:
    list.add_item(i, onclick=login_page, chevron= True  )

def getssid():
  command = "nmcli -t -f ssid dev wifi| cut -d\\' -f2"  
  process = subprocess.check_output("nmcli -t -f ssid dev wifi| cut -d\\' -f2", shell=True)
  namelist= process.split('\n')
  for i in namelist:
    if i not in noduplist:
      noduplist.append(i)
  print noduplist
class DoorControl(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "chickens.png"

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Control",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Open Or Close Chicken Coop Door!",
                                           "h1")
        timer_start = self.page.add_button("Start Timer",
                                           self.start_timer)
        timer_stop = self.page.add_button("Stop Timer",
                                          self.stop_timer)
        up = self.page.add_button("Open &uarr;", self.onupclick)
        down = self.page.add_button("Close &darr;", self.ondownclick)
        fup = self.page.add_button("Force Open &uarr;", self.onupforceclick)
        fdown = self.page.add_button("Force Close &darr;",
                                     self.ondownforceclick)
        stop = self.page.add_button("Stop Door", self.onstopclick)
        kill = self.page.add_button("Kill Server", self.onkillclick)
        self.img = self.page.add_image("chickens.png")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="Chicken Control Center")
        self.list = self.page.add_list()
        self.list.add_item("Control", chevron=True,
                           onclick=self.page_buttons)
        self.ui.done()

    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Opening")
        print "Open"
        moveDoor(direction=OPEN)

    def ondownclick(self):
        self.title.set_text("Closing")
        print "Close"
        moveDoor(direction=CLOSE)

    def onupforceclick(self):
        self.title.set_text("Force Open")
        print "Force Open"
        moveDoor(direction=OPEN, force=True)

    def ondownforceclick(self):
        self.title.set_text("Force Close")
        print "Force Close"
        moveDoor(direction=CLOSE, force=True)

    def onstopclick(self):
        self.title.set_text("Stopping Door")
        print "Stopping"
        stopDoor()

    def onkillclick(self):
        self.title.set_text("Killing Server")
        print "Killing"
        time.sleep(0.5)
        killSystem()

    def control_timer(self, start=True):
        global timer_running
        global stop_timer
        if start and timer_running or not start and not timer_running:
            return
        if start:
            timer_running = True
            stop_timer = False
        else:
            stop_timer = True
            return
        seconds_since_last_action = 999
        [open_hour, open_minute] = OPEN_TIME.split(":")
        [close_hour, close_minute] = CLOSE_TIME.split(":")
        while True and not stop_timer:

            # Wait until the specified time and then open or close the
            # door depending on the specified direction

            # Get current time
            now = datetime.datetime.now()

            # Make sure at least two minutes have passed since the last action
            if seconds_since_last_action > 120:
                print ("(%d)  now.hour:%s  now.minute:%s  open_hour:%s  "
                       "open_minute:%s  close_hour:%s  close_minute:%s" %
                       (seconds_since_last_action, str(now.hour),
                        str(now.minute), open_hour, open_minute,
                        close_hour, close_minute))
                # If it's time, perform the action and reset the timer
                if (now.hour == int(open_hour) and
                        now.minute == int(open_minute)):
                    print "Opening at %s:%s" % (str(now.hour), str(now.minute))
                    moveDoor(direction=OPEN)
                    seconds_since_last_action = 0
                    # Reset timer
                if (now.hour == int(close_hour) and
                        now.minute == int(close_minute)):
                    print "Closing at %s:%s" % (str(now.hour), str(now.minute))
                    moveDoor(direction=CLOSE)
                    seconds_since_last_action = 0

            # Sleep for 1 second before checking again
            time.sleep(1)
            seconds_since_last_action += 1
        timer_running = False

    def start_timer(self):
        self.control_timer(start=True)

    def stop_timer(self):
        self.control_timer(start=False)

    GPIO.add_event_detect(BUTTON, GPIO.RISING, callback=buttonCallback,
                          bouncetime=300)
Example #19
0
class PiUiTestCase(unittest.TestCase):

    def setUp(self):
        self._ui = PiUi("Test", timeout=1)

    def tearDown(self):
        print "tearDown"
        self._ui.exit()

    def http_get(self, rel_url):
        handler = urllib2.urlopen('http://localhost:9999/' + rel_url)
        return handler.getcode(), handler.read()

    def click(self):
        self._clicked = True

    def test_menu(self):
        self.page = self._ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content", chevron=True, onclick=self.click)
        self.list.add_item("Buttons", chevron=True, onclick=self.click)
        self.list.add_item("Input", chevron=True, onclick=self.click)
        self.list.add_item("Images", chevron=True, onclick=self.click)
        self.list.add_item("Toggles", chevron=True, onclick=self.click)
        self.list.add_item("Console!", chevron=True, onclick=self.click)
        resp = self.http_get('/')
        assert "initPiUi();" in resp[1]
        resp = self.http_get('/init')
        assert "ok" in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "newpage"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "pagepost"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addul"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addli"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "timeout"' in resp[1]

    def test_clicks(self):
        self._clicked = False
        self.page = self._ui.new_ui_page(title="PiUi")
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Test Button", self.click)
        resp = self.http_get('/')
        assert "initPiUi();" in resp[1]
        resp = self.http_get('/init')
        assert "ok" in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "newpage"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "pagepost"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addelement"' in resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "addbutton"' in resp[1]
        btn_cmd = resp[1]
        resp = self.http_get('/poll')
        assert '"cmd": "timeout"' in resp[1]
        decoder = json.JSONDecoder()
        cmd = decoder.decode(btn_cmd)
        self.http_get('/click?eid=' + cmd['eid'])
        assert self._clicked
Example #20
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content", prev_text="Back",
            onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project", "h1")
        self.page.add_element("hr")
        self.page.add_textbox("You can use any static HTML element " + 
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.", "p")
        self.page.add_element("hr")
        self.page.add_textbox("Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 10):
            update.set_text(str(a))
            time.sleep(1)


    def page_smalltalk(self):
        self.page = self.ui.new_ui_page(title="Small Talk", prev_text="Back", onprevclick=self.main_menu)

        self.title = self.page.add_textbox("Small Talk Questions", "h1")
        bq1 = self.page.add_button("HowAreYou", self.q1)
        bq2 = self.page.add_button("TellMe", self.q2)
        bq3 = self.page.add_button("Brothers/Sisters", self.q3)
        bq4 = self.page.add_button("Pets", self.q4)
        bq5 = self.page.add_button("Birthday", self.q5)
        bq6 = self.page.add_button("Grade", self.q6)
        bq7 = self.page.add_button("Breakfast", self.q7)
        bq8 = self.page.add_button("School", self.q8)
        self.title = self.page.add_textbox("Small Talk Answers", "h1")
        b1 = self.page.add_button("ImGood", self.a1)
        b2 = self.page.add_button("ImOkay", self.a2)
        b3 = self.page.add_button("NotGreat", self.a3)
        b4 = self.page.add_button("AboutMe", self.a4)
        b5 = self.page.add_button("Brothers/Sisters", self.a5)
        b6 = self.page.add_button("Pets", self.a6)
        b7 = self.page.add_button("Birthday", self.a7)
        b8 = self.page.add_button("Grade", self.a8)
        b9 = self.page.add_button("Breakfast", self.a9)
        b10 = self.page.add_button("School", self.a10)
        self.title = self.page.add_textbox("Output String", "h1")


    def page_introexitgeneric(self):
        self.page = self.ui.new_ui_page(title="Intro Exit Generic", prev_text="Back", onprevclick=self.main_menu)

        self.title = self.page.add_textbox("Intro", "h1")
        inb1 = self.page.add_button("Hello", self.in1)
        inb2 = self.page.add_button("Intro", self.in2)
        self.title = self.page.add_textbox("Exit", "h1")
        exb1 = self.page.add_button("Bye", self.ex1)
        exb2 = self.page.add_button("See you", self.ex2)
        self.title = self.page.add_textbox("Generic", "h1")
        geb1 = self.page.add_button("Don'tKnow", self.ge1)
        geb2 = self.page.add_button("Yes", self.ge2)
        geb3 = self.page.add_button("No", self.ge3)
        geb4 = self.page.add_button("Sorry", self.ge4)
        geb5 = self.page.add_button("HowAbout", self.ge5)
        geb6 = self.page.add_button("MeToo", self.ge6)
        geb7 = self.page.add_button("Why?", self.ge7)
        geb8 = self.page.add_button("Maybe", self.ge8)
        self.title = self.page.add_textbox("Output String", "h1")



    def page_buttons(self):
        img = cv2.imread('imgs/lena.jpg',0)
        cv2.imshow('image',img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        self.page = self.ui.new_ui_page(title="Buttons", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images", prev_text="Back", onprevclick=self.main_menu)
        self.img = self.page.add_image("lena.jpg")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles", prev_text="Back", onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")
        

    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")


    #function to get ID from filename
    def ID_from_filename(filename):
        part = string.split(filename, '/')
        return part[1].replace("s", "")
     
    #function to convert image to right format
    def prepare_image(filename):
        img_color = cv2.imread(filename)
        img_gray = cv2.cvtColor(img_color, cv2.cv.CV_RGB2GRAY)
        img_gray = cv2.equalizeHist(img_gray)
        return img_gray.flat

    def page_video(self):
        self.page = self.ui.new_ui_page(title="Video", prev_text="Back", onprevclick=self.main_menu)
        # initialize the camera and grab a reference to the raw camera capture
        camera = PiCamera()
        camera.resolution = (320, 240)
        camera.framerate = 5
        rawCapture = PiRGBArray(camera, size=(320, 240))
         
        # allow the camera to warmup
        time.sleep(0.1)
         
        # capture frames from the camera
        for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
            # grab the raw NumPy array representing the image, then initialize the timestamp
            # and occupied/unoccupied text
            image = frame.array
         
            # show the frame
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(gray, 1.3, 5)
            for (x,y,w,h) in faces:
                cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
                roi_gray = gray[y:y+h, x:x+w]
                roi_color = image[y:y+h, x:x+w]
                eyes = eye_cascade.detectMultiScale(roi_gray)
                for (ex,ey,ew,eh) in eyes:
                    cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
                    test_val = ex 
            cv2.imshow("Frame", image)


            count = 0
            if (count < 10 and ex != null):
                resized_image = cv2.resize(image, (92, 112)) 
                cv2.imwrite("face-" + str(count) + ".jpg", resized_image)
                #take photos here
                

            key = cv2.waitKey(1) & 0xFF
         
            # clear the stream in preparation for the next frame
            rawCapture.truncate(0)
            # if the `q` key was pressed, break from the loop
            if key == ord("q"):
                break

    # positive feedback, uhoh i didn't say
    #intro, exit generic responses


    def page_simonsays(self):
        self.page = self.ui.new_ui_page(title="Simon Says", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Simon Says", "h1")
        ssq1 = self.page.add_button("Hands/head", self.ss1)
        ssq2 = self.page.add_button("Touch Nose", self.ss2)
        ssq3 = self.page.add_button("Spin", self.ss3)
        ssq4 = self.page.add_button("Hands/hip", self.ss4)
        ssq5 = self.page.add_button("Touch/knees", self.ss5)
        ssq6 = self.page.add_button("Jump", self.ss6)
        ssq7 = self.page.add_button("Hands/high", self.ss7)
        ssq8 = self.page.add_button("Touch/toes", self.ss8)
        ssq9 = self.page.add_button("Rub/tum", self.ss9)
        ssq10 = self.page.add_button("Clap", self.ss10)
        ssq11 = self.page.add_button("Run", self.ss11)
        ssq12 = self.page.add_button("Stomp", self.ss12)
        self.title = self.page.add_textbox("Simon Didn't Say", "h1")
        sdsq1 = self.page.add_button("Hands/head", self.sds1)
        sdsq2 = self.page.add_button("Touch Nose", self.sds2)
        sdsq3 = self.page.add_button("Spin", self.sds3)
        sdsq4 = self.page.add_button("Hands/hip", self.sds4)
        sdsq5 = self.page.add_button("Touch/knees", self.sds5)
        sdsq6 = self.page.add_button("Jump", self.sds6)
        sdsq7 = self.page.add_button("Hands/high", self.sds7)
        sdsq8 = self.page.add_button("Touch/toes", self.sds8)
        sdsq9 = self.page.add_button("Rub/tum", self.sds9)
        sdsq10 = self.page.add_button("Clap", self.sds10)
        sdsq11 = self.page.add_button("Run", self.sds11)
        sdsq12 = self.page.add_button("Stomp", self.sds12)
        self.title = self.page.add_textbox("Output String", "h1")

    def page_feedback(self):
        self.page = self.ui.new_ui_page(title="Feedback", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Uh-oh...I didn't say", "h1")

        fnb1 = self.page.add_button("Uh-oh", self.fn1)
        fnb2 = self.page.add_button("Sorry", self.fn2)
        fnb3 = self.page.add_button("Too bad", self.fn3)
        fnb4 = self.page.add_button("Got you!", self.fn4)
        fnb5 = self.page.add_button("No, no", self.fn5)
        fnb6 = self.page.add_button("I saw you!", self.fn6)
        fnb7 = self.page.add_button("Didn't say", self.fn7)
        fnb8 = self.page.add_button("Oh no", self.fn8)

        self.title = self.page.add_textbox("Positive Feedback", "h1")
        fpb1 = self.page.add_button("Way to go!", self.fp1)
        fpb2 = self.page.add_button("Awesome", self.fp2)
        fpb3 = self.page.add_button("You did it!", self.fp3)
        fpb4 = self.page.add_button("Excellent!", self.fp4)
        fpb5 = self.page.add_button("Smart!", self.fp5)
        fpb6 = self.page.add_button("Terrfic!", self.fp6)
        fpb7 = self.page.add_button("The best!", self.fp7)
        fpb8 = self.page.add_button("Great!", self.fp8)

        self.title = self.page.add_textbox("Output String", "h1")

    def page_headeyes(self):
        self.page = self.ui.new_ui_page(title="Head Eyes", prev_text="Back", onprevclick=self.main_menu)
        heq1 = self.page.add_button("Blink", self.he1)
        heq2 = self.page.add_button("Wink", self.he2)
        heq3 = self.page.add_button("Head Right", self.he3)
        heq4 = self.page.add_button("Head Left", self.he4)
        heq5 = self.page.add_button("Center", self.he5)
        self.title = self.page.add_textbox("Output Action", "h1")


    def page_storytelling(self):
        self.page = self.ui.new_ui_page(title="Story Telling", prev_text="Back", onprevclick=self.main_menu)
        stb1 = self.page.add_button("TellMe", self.st1)
        stb2 = self.page.add_button("CanITell", self.st2)
        stb3 = self.page.add_button("Another", self.st3)
        stb4 = self.page.add_button("Story1", self.st4)
        stb5 = self.page.add_button("Story2", self.st5)
        self.title = self.page.add_textbox("Output Action", "h1")


    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        #self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Small Talk", chevron=True, onclick=self.page_smalltalk)
        self.list.add_item("Head Eyes", chevron=True, onclick=self.page_headeyes)
        self.list.add_item("Simon Says", chevron=True, onclick=self.page_simonsays)
        self.list.add_item("Feedback", chevron=True, onclick=self.page_feedback)
        self.list.add_item("Intro Exit Generic", chevron=True, onclick=self.page_introexitgeneric)
        self.list.add_item("Story Telling", chevron=True, onclick=self.page_storytelling)
        #self.list.add_item("Input", chevron=True, onclick=self.page_input)
        #self.list.add_item("Images", chevron=True, onclick=self.page_images)
        #self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.list.add_item("Video", chevron=True, onclick=self.page_video)
        self.ui.done()


    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def st1(self):
        self.title.set_text("Why don't you tell me a story!")
        print "Why don't you tell me a story!"

    def st2(self):
        self.title.set_text("Do you wanna hear a story?")
        print "Do you wanna hear a story?"

    def st3(self):
        self.title.set_text("Do you want to hear another story?")
        print "Do you want to hear another story?"

    def st4(self):
        self.title.set_text("One time, I was at a pool party.  It was my friend Jimmy's birthday, and he decided we should play a game. He dropped these jewels at the bottom of the pool, and you had to see how many you could collect in thirty seconds. Most people got around five.  But my friend Andy?  He was underwater for so long, we weren't sure if something had happened! We were about to send someone in to look for him, when all of a sudden, he popped out of the pool.  He said he saw something sparkling at the bottom and thought it was a jewel, but it was covered under some dirt at the bottom of the pool, so he had to scrape it out.  And guess what?  He found a necklace Jimmy's sister dropped in the pool a long time ago!  We were all looking for Jewels, but, really, it was Andy who found the real treasure!")
        print "One time, I was at a pool party.  It was my friend Jimmy's birthday, and he decided we should play a game. He dropped these jewels at the bottom of the pool, and you had to see how many you could collect in thirty seconds. Most people got around five.  But my friend Andy?  He was underwater for so long, we weren't sure if something had happened! We were about to send someone in to look for him, when all of a sudden, he popped out of the pool.  He said he saw something sparkling at the bottom and thought it was a jewel, but it was covered under some dirt at the bottom of the pool, so he had to scrape it out.  And guess what?  He found a necklace Jimmy's sister dropped in the pool a long time ago!  We were all looking for Jewels, but, really, it was Andy who found the real treasure!"

    def st5(self):
        self.title.set_text("Once, I had a playdate at my friend Alex's house and we really wanted to bake something. We both liked cookies and pizza, so we thought it would be an awesome idea to bake a cookie pizza! I used chocolate chips, mini oreos, marshmallows, and peanut butter chips as my toppings. Alex made a crazy pizza with gummy worms, M and M's, and bacon. Those were the weirdest cookie toppings I had ever seen. We put our cookie pizzas in the oven, and once they were done, we were so hungry, we ate 4 slices! I tried some of Alex's cookie pizza, and it was actually pretty good. Maybe I'll try making a crazy cookie pizza next time. That was one of the best playdates I've ever had.")
        print "Once, I had a playdate at my friend Alex's house and we really wanted to bake something. We both liked cookies and pizza, so we thought it would be an awesome idea to bake a cookie pizza! I used chocolate chips, mini oreos, marshmallows, and peanut butter chips as my toppings. Alex made a crazy pizza with gummy worms, M and M's, and bacon. Those were the weirdest cookie toppings I had ever seen. We put our cookie pizzas in the oven, and once they were done, we were so hungry, we ate 4 slices! I tried some of Alex's cookie pizza, and it was actually pretty good. Maybe I'll try making a crazy cookie pizza next time. That was one of the best playdates I've ever had."

    def in1(self):
        self.title.set_text("Hi!  My name is L-E and I love to play Simon Says.  Would you like to play with me?")
        print "Hi!  My name is L-E and I love to play Simon Says.  Would you like to play with me?"

    def in2(self):
        self.title.set_text("Ok great!  I'll be Simon!  When I say Simon Says, you do what I say.  But if I don't say Simon Says, then you shouldn't do it.  Ok?")
        print "Ok great!  I'll be Simon!  When I say Simon Says, you do what I say.  But if I don't say Simon Says, then you shouldn't do it.  Ok?"

    def ex1(self):
        self.title.set_text("Bye addNameVar. That was fun!")
        print "Bye addNameVar. That was fun!"

    def ex2(self):
        self.title.set_text("Bye addNameVar. That was fun!")
        print "See you next time addNameVar."

    def ge1(self):
        self.title.set_text("I don't know")
        print "I don't know"

    def ge2(self):
        self.title.set_text("Yes")
        print "Yes"

    def ge3(self):
        self.title.set_text("No")
        print "No"

    def ge4(self):
        self.title.set_text("Sorry")
        print "Sorry"

    def ge5(self):
        self.title.set_text("How about you?")
        print "How about you?"

    def ge6(self):
        self.title.set_text("Me too")
        print "Me too"

    def ge7(self):
        self.title.set_text("Why")
        print "Why"

    def ge8(self):
        self.title.set_text("Maybe")
        print "Maybe"

    def fn1(self):
        self.title.set_text("Uh-Oh... I didn't say Simon Says!")
        print "Uh-Oh... I didn't say Simon Says!"

    def fn2(self):
        self.title.set_text("I'm sorry but I didn't say Simon Says!... make sure you listen closely!")
        print "I'm sorry but I didn't say Simon Says!... make sure you listen closely!"

    def fn3(self):
        self.title.set_text("Oh no!... you moved but I never said Simon Says!  Ok, here we go again...")
        print "Oh no!... you moved but I never said Simon Says!  Ok, here we go again..."

    def fn4(self):
        self.title.set_text("I got you!  I didn't say Simon Says this time...  this is fun!  Let's keep going!")
        print "I got you!  I didn't say Simon Says this time...  this is fun!  Let's keep going!"

    def fn5(self):
        self.title.set_text("No-No-No, I didn't say it!  That's ok though, you are doing great!  Let's play again!")
        print "No-No-No, I didn't say it!  That's ok though, you are doing great!  Let's play again!"

    def fn6(self):
        self.title.set_text("HA-ha-ha! I saw you! You moved but I didn't say Simon Says!, This is so much fun! Let's play again!")
        print "HA-ha-ha! I saw you! You moved but I didn't say Simon Says!, This is so much fun! Let's play again!"
        
    def fn7(self):
        self.title.set_text("OOPS! I think you moved but I didn't say Simon Says! Ok, let's keep going!")
        print "OOPS! I think you moved but I didn't say Simon Says! Ok, let's keep going!"

    def fn8(self):
        self.title.set_text("Oh-oh-oh! Too bad, so sad. I got you!! Next time, wait until I say Simon Says before you move!")
        print "Oh-oh-oh! Too bad, so sad. I got you!! Next time, wait until I say Simon Says before you move!"

    def fp1(self):
        self.title.set_text("Way to go! That was perfect! Let's play again!")
        print "Way to go! That was perfect! Let's play again!"

    def fp2(self):
        self.title.set_text("You are awesome! Great listening! Let's keep going!")
        print "You are awesome! Great listening! Let's keep going!"

    def fp3(self):
        self.title.set_text("You did it! Fabulous! Should we keep playing?")
        print "You did it! Fabulous! Should we keep playing?"

    def fp4(self):
        self.title.set_text("Excellent! You are listening so well and did it perfectly! Let's keep playing!")
        print "Excellent! You are listening so well and did it perfectly! Let's keep playing!"

    def fp5(self):
        self.title.set_text("You are very smart! I couldn't trick you once! Let's play again!")
        print "You are very smart! I couldn't trick you once! Let's play again!"

    def fp6(self):
        self.title.set_text("That was terrific! Another amazing performance! Do you want to keep playing with me?")
        print "That was terrific! Another amazing performance! Do you want to keep playing with me?"
        
    def fp7(self):
        self.title.set_text("You are the best! Incredible! Let's do it again!")
        print "You are the best! Incredible! Let's do it again!"

    def fp8(self):
        self.title.set_text("Great! You are truly awesome. Here we go again! Are you ready?")
        print "Great! You are truly awesome. Here we go again! Are you ready?"

    def ss1(self):
        self.title.set_text("Simon says, put your hands on your head!")
        print "Simon says, put your hands on your head!"

    def ss2(self):
        self.title.set_text("Simon says, Touch your nose!")
        print "Simon says, Touch your nose!"

    def ss3(self):
        self.title.set_text("Simon says, turn all the way around!")
        print "Simon says, turn all the way around!"

    def ss4(self):
        self.title.set_text("Simon says, place your hands on your hips!")
        print "Simon says, place your hands on your hips!"

    def ss5(self):
        self.title.set_text("Now Simon says, Touch your knees!")
        print "Now Simon says, Touch your knees!"

    def ss6(self):
        self.title.set_text("Simon says, jump three times!")
        print "Simon says, jump three times!"

    def ss7(self):
        self.title.set_text("Ok, Simon says, Hold your hands up high!")
        print "Ok, Simon says, Hold your hands up high!"

    def ss8(self):
        self.title.set_text("Simon says, touch your toes!")
        print "Simon says, touch your toes!"

    def ss9(self):
        self.title.set_text("Simon says, rub your tummy!")
        print "Simon says, rub your tummy!"

    def ss10(self):
        self.title.set_text("Simon says, Clap your hands!")
        print "Simon says, Clap your hands!"

    def ss11(self):
        self.title.set_text("And Simon says, run in place!")
        print "And Simon says, run in place!"

    def ss12(self):
        self.title.set_text("Simon says, stomp your feet!")
        print "Simon says, stomp your feet!"

    #simon didn't say...
    def sds1(self):
        self.title.set_text("Put your hands on your head!")
        print "Put your hands on your head!"

    def sds2(self):
        self.title.set_text("Touch your nose!")
        print "Touch your nose!"

    def sds3(self):
        self.title.set_text("Turn all the way around!")
        print "Turn all the way around!"

    def sds4(self):
        self.title.set_text("Put your hands on your hips!")
        print "Put your hands on your hips!"

    def sds5(self):
        self.title.set_text("Touch your knees!")
        print "Touch your knees!"

    def sds6(self):
        self.title.set_text("Now, jump three times!")
        print "Now, jump three times!"

    def sds7(self):
        self.title.set_text("Hold your hands up high!")
        print "Hold your hands up high!"

    def sds8(self):
        self.title.set_text("Now, touch your toes!")
        print "Now, touch your toes!"

    def sds9(self):
        self.title.set_text("Everyone rub your tummy!")
        print "Everyone rub your tummy!"

    def sds10(self):
        self.title.set_text("Clap your hands!")
        print "Clap your hands!"

    def sds11(self):
        self.title.set_text("Ok, run in place!")
        print "Ok, run in place!"

    def sds12(self):
        self.title.set_text("Let's stomp your feet!")
        print "Let's stomp your feet!"


    def he1(self):
        self.title.set_text("Blink")
        print "Blink"
        
    def he2(self):
        self.title.set_text("Wink")
        print "Wink"

    def he3(self):
        self.title.set_text("Head Right")
        print "Head Right"

    def he4(self):
        self.title.set_text("Head Left")
        print "Head Left"

    def he5(self):
        self.title.set_text("Center")
        print "Center"

    def a1(self):
        self.title.set_text("I'm good")
        print "I'm good"

    def a2(self):
        self.title.set_text("I'm okay")
        print "I'm okay"

    def a3(self):
        self.title.set_text("Not great. I'm having trouble figuring out some math problems I was assigned")
        print "Not great.  I'm having trouble figuring out some math problems I was assigned"

    def a4(self):
        self.title.set_text("Well, I love reading and watching TV.  I can't do everything humans can do because I'm a robot, but I love playing wit humans like you!")
        print "Well, I love reading and watching TV.  I can't do everything humans can do because I'm a robot, but I love playing wit humans like you!"

    def a5(self):
        self.title.set_text("Robots don't really have brothers and sisters, but there are others like me out there! I like to think of them as my brothers and sisters.")
        print "Robots don't really have brothers and sisters, but there are others like me out there! I like to think of them as my brothers and sisters."

    def a6(self):
        self.title.set_text("I wish! I think dogs are really fun.")
        print "I wish! I think dogs are really fun."

    def a7(self):
        self.title.set_text("I was created on May 15")
        print "I was created on May 15"

    def a8(self):
        self.title.set_text("Robots can go to school with kids from all different grades, but I'm eight!")
        print "Robots can go to school with kids from all different grades, but I'm eight!"

    def a9(self):
        self.title.set_text("I didn't have breakfast today, but I love doughnuts!")
        print "I didn't have breakfast today, but I love doughnuts!"

    def a10(self):
        self.title.set_text("Today, I learned about the sea.  Did you know that a shark is the only known fish that can blink with both eyes?")
        print "Today, I learned about the sea.  Did you know that a shark is the only known fish that can blink with both eyes?"

    def q1(self):
        self.title.set_text("How are you")
        print "How are you"

    def q2(self):
        self.title.set_text("Tell me about yourself")
        print "Tell me about yourself"

    def q3(self):
        self.title.set_text("Do you have any brothers or sisters?")
        print "Do you have any brothers or sisters?"

    def q4(self):
        self.title.set_text("Do you have any pets")
        print "Do you have any pets"

    def q5(self):
        self.title.set_text("When is your birthday?")
        print "When is your birthday?"

    def q6(self):
        self.title.set_text("What grade are you in?")
        print "What grade are you in?"

    def q7(self):
        self.title.set_text("What did you have for breakfast today?")
        print "What did you have for breakfast today?"

    def q8(self):
        self.title.set_text("What did you do in school today?")
        print "What did you do in school today?"
        

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"

    def onhelloclick(self):
        print "onstartclick"
        self.title.set_text("Hello " + self.txt.get_text())
        print "Start"

    def onpicclick(self):
        if self.src == "sunset.png":
          self.img.set_src("sunset2.png")
          self.src = "sunset2.png"
        else:
          self.img.set_src("sunset.png")
          self.src = "sunset.png"

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))
Example #21
0
 def __init__(self):
     self.title = None
     self.txt = None
     self.img = None
     self.ui = PiUi()
Example #22
0
class RocketPiUi(object):
    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi()

    def main_page(self):
        self.page = self.ui.new_ui_page(title="VC Rocketry Live Update")

        self.page.add_textbox("Location", "h1")
        update1 = self.page.add_textbox("0.0, 0.0", "p")
        self.page.add_element("hr")

        self.page.add_textbox("Speed and Acceleration", "h1")
        update2 = self.page.add_textbox("Speed: 0.0, Acceleration: 0.0", "p")
        self.page.add_element("hr")

        self.page.add_textbox("Rocket Mode", "h1")
        update3 = self.page.add_textbox("Prechecks")
        self.page.add_element("hr")

        self.page.add_textbox("Squib Status", "h1")
        update4 = self.page.add_textbox("Not Deployed")
        self.page.add_element("hr")

        self.page.add_textbox("9 Volt Current Flowing", "h1")
        update5 = self.page.add_textbox("False")
        self.page.add_element("hr")

        for i in range(0, 50):
            # latitude = frame[-1]["latitude"]
            # longitude = frame[-1]["longitude"]
            # speed = frame[-1]["speed"]
            # acceleration = math.sqrt((frame[-1]["a_x"]*9.81)**2 + (frame[-1]["a_y"]*9.81)**2 + (frame[-1]["a_z"]*9.81)**2)
            # global flightMode
            # global squibDeployed
            # current = frame[-1]["current_1"]

            # This is dummy data, remove these varibales and uncomment the ones above for real testing
            # You will, of course, have to remove this code from the for loop
            flightMode = i
            squibDeployed = i
            x = float(i)
            latitude = x
            longitude = x
            speed = x
            acceleration = x
            current = x

            update1.set_text(str(latitude) + ", " + str(longitude))

            update2.set_text("Speed: " + str(speed) + " ft/s" +
                             ", Acceleration: " + str(acceleration) + " m/s^2")

            if flightMode == 0:
                update3.set_text("Pre-Check 1")
            elif flightMode == 1:
                update3.set_text("Pre-Check 2")
            elif flightMode == 2:
                update3.set_text("Flight")
            elif flightMode == 3:
                update3.set_text("Descent")
            elif flightMode == 4:
                update3.set_text("Recovery")

            if squibDeployed == 1:
                update4.set_text("Deployed")

            if (current > 0.0):
                update5.set_text("True")
            else:
                update5.set_text("False")
            sleep(1)

        self.ui.done()

    def main(self):
        self.main_page()
        self.ui.done()
 def __init__(self):
     self.ui = PiUi()
Example #24
0
import logging
import os
import subprocess
import time
import json

from piui import PiUi

import RFStatusCheck

ui = PiUi()
page = ui.new_ui_page(title="RFConnect")
log_file = 'RFServer/log/rfserver.log'

current_dir = os.path.dirname(os.path.abspath(__file__))

# Sets up logger with the configured log file
def setup_logger(logfile, verbose, console):
    if verbose:
        log_level = logging.DEBUG
    else:
        log_level = logging.INFO

    logging.getLogger('').handlers = []
    logging.basicConfig(level=log_level,
                        format='RFSERV~[%(levelname)s] %(asctime)s, %(message)s',
                        datefmt='%Y-%m-%d-%H:%M:%S',
                        filename=logfile,
                        filemode='w+')
    if console:
        console = logging.StreamHandler()
Example #25
0
class DemoPiUi(object):

    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content", prev_text="Back",
            onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project", "h1")
        self.page.add_element("hr")
        self.page.add_textbox("You can use any static HTML element " + 
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.", "p")
        self.page.add_element("hr")
        self.page.add_textbox("Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 5):
            update.set_text(str(a))
            time.sleep(1)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input", prev_text="Back", onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images", prev_text="Back", onprevclick=self.main_menu)
        self.img = self.page.add_image("sunset.png")
        self.page.add_element('br')
        button = self.page.add_button("Change The Picture", self.onpicclick)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles", prev_text="Back", onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave", chevron=False, toggle=True, ontoggle=functools.partial(self.ontoggle, "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")
        

    def page_console(self):
        con = self.ui.console(title="Console", prev_text="Back", onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content", chevron=True, onclick=self.page_static)
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()


    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"

    def onhelloclick(self):
        print "onstartclick"
        self.title.set_text("Hello " + self.txt.get_text())
        print "Start"

    def onpicclick(self):
        if self.src == "sunset.png":
          self.img.set_src("sunset2.png")
          self.src = "sunset2.png"
        else:
          self.img.set_src("sunset.png")
          self.src = "sunset.png"

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))
Example #26
0
class RFServerUI(object):

    def __init__(self):
        self.page = None
        self.title = None
        self.txt = None
        self.status_head = None
        self.status_title = None
        self.status_txt = None
        self.action_txt = None
        self.download_title = None
        self.download_link = None
        self.img = None
        self.ui = PiUi()
        self.src = None
        self.rfstatus = RFStatusCheck.RFStatusCheck()

        self.status_states = {
            0 : '<p style=\"color:SlateGray;font-style:italic;\">Checking Status...</p>',
            1 : '<p style=\"color:blue;font-weight:normal;\">Waiting to scan inventory.</p>',
            2 : '<p style=\"color:LimeGreen;font-weight:bold;\">Inventory scan in progress.</p>',
            3 : '<p style=\"color:blue;font-weight:bold;\">Inventory scan completed successfully.</p>',
            4 : '<p style=\"color:red;font-weight:bold;\">Inventory scan failed.</p>'
        }

        self.action_states = {
            0 : '<p>&nbsp;</p>',
            1 : '<p style=\"color:SlateGray;font-style:italic;\">Starting Data Collection...</p>',
            2 : '<p style=\"color:DarkSlateGray;font-weight:normal;\">Inventory scan is already running.</p>',
            3 : '<p style=\"color:SlateGray;font-style:italic;\">Stopping Data Collection...</p>',
            4 : '<p style=\"color:DarkSlateGray;font-weight:normal;\">Inventory scan is not running.</p>'
        }
        self.status_state = 0
        self.action_state = 0

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="RFConnect")
        self.title = self.page.add_textbox("RFID Inventory Controller", "h1")
        self.page.add_textbox("<br>", "p")
        start = self.page.add_button("Start Inventory Scan", self.on_start_click)
        stop = self.page.add_button("End Data Collection", self.on_stop_click)
        self.action_txt = self.page.add_textbox("<br>", "p")
        self.page.add_textbox("<br>", "p")
        self.download_title = self.page.add_textbox("<p></p>", "h2")
        self.download_link = self.page.add_textbox("<a></a>", "a")

        self.page.add_textbox("Inventory Scan Status:", "h2")
        refresh = self.page.add_button("Refresh Scan Status", self.on_refresh_click)
        self.page.add_textbox("<br>", "p")
        self.status_title = self.page.add_textbox("<p></p>", "p")
        self.status_txt = self.page.add_textbox("<br>", "p")
        self.status_state = 0
        self.action_state = 0
        time.sleep(1)
        status = self.refresh_state()

    def refresh_action_state(self):
        action = self.action_state

        if action is 0:
            pass

        elif action is 1:
            if self.status_state is 2:
                self.action_state = 0

        elif action is 2:
            pass

        elif action is 3:
            if self.status_state is 3 or self.status_state is 4:
                self.action_state = 0
        elif action is 4:
            pass

        self.action_txt.set_text(self.action_states[self.action_state])

    def refresh_state(self):
        status = self.update_status_state()
        self.status_title.set_text(self.status_states[self.status_state])
        text = '<br>'

        if status is 0:
            text = '<br>'

        elif status is 1:
            text = '<br>'

        elif status is 2:
            # show tags in a table as they come in
            text = '<p>Started: %s</p>' % self.rfstatus.read_start_time()
            text += '<p>Current runtime: %d minutes, %d seconds</p>' % self.rfstatus.calculate_runtime()
            if self.rfstatus.has_written_file('.json'):
                #print tag progress
                text += '<br><p>RFID Tags Captured:</p>'
                text += self.build_tag_table()

        elif status is 3:
        # retrieve output file
            text = '<p>Started: %s</p>' % self.rfstatus.read_start_time()
            text += '<p>Runtime: %d minutes, %d seconds</p>' % self.rfstatus.calculate_final_runtime()
            if self.rfstatus.has_written_file('.json'):
                # print tag progress
                text += '<br><p>RFID Tags Captured:</p>'
                text += self.build_tag_table()

            #if self.rfstatus.has_written_file('.xlsx'):
            #   self.download_title.set_text('Inventory Scan Report')
            #    dl_path = self.resolve_dl_path('.xlsx')
            #    dl_element = '<a href=\"%s\" download>Click to download</a>' % dl_path
            #    self.download_link.set_text(dl_element)

        elif status is 4:
        # display error
            text = '<p>Details: %s</p>' % self.rfstatus.read_error()

        self.refresh_action_state()
        self.status_txt.set_text(text)
        return status

    def on_refresh_click(self):
        self.status_title.set_text(self.status_states[0])
        status = self.refresh_state()
        while status is 0:
            time.sleep(0.5)
            status = self.refresh_state()

    def on_start_click(self):
        logging.info('Start button clicked')
        self.refresh_state()

        #if inventory scan already running
        if self.status_state is 2:
            self.action_state = 2
            self.refresh_state()
        else:
            self.action_state = 1
            self.refresh_action_state()
            logging.info("executing: \'./start_collection.sh\'")
            subprocess.call('./start_collection.sh', shell=True)
            status = self.refresh_state()
            while status is not 2:
                time.sleep(0.5)
                status = self.refresh_state()

    def on_stop_click(self):
        logging.info('Stop button clicked')
        self.refresh_state()

        # if inventory scan not running
        if self.status_state is not 2:
            self.action_state = 4
            self.refresh_state()
        else:
            self.action_state = 3
            self.refresh_action_state()
            logging.info("executing: \'./end_collection.sh\'")
            subprocess.call('./end_collection.sh', shell=True)
            status = self.refresh_state()
            while status is 0 or status is 2:
                time.sleep(0.5)
                status = self.refresh_state()


    def update_status_state(self):
        state = self.rfstatus.check_rf_state()
        self.status_state = state
        return state

    def build_tag_table(self):
        table = '<table style=\"width:100%\" border="1">'
        try:
            json_file = self.rfstatus.read_file_name('.json')
            logging.info("json file: %s" % json_file)
            json_data = self.rfstatus.read_tag_file(json_file)
            logging.info ("json: %s" % json_data)
            tag_map = json.loads(json_data)['RF Tags Identified']['data']

            table += '<tr><th style=\"text-align:left;\">Tag ID</th>'
            table += '<th style=\"text-align:left;\">Time Last Seen</th></tr>'
            for tag in tag_map:
                table += '<tr><td>' + str(tag) + '</td><td>' + str(tag_map[tag]) + '</td></tr>'
            table += '</table>'
            return table
        except:
            return '<p style=\"color:SlateGray;font-style:italic;\">loading tags table...</p>'

    def resolve_dl_path(self, extension):
        filename = self.rfstatus.read_file_name(extension)
        return self.rfstatus.get_scan_data_path() + filename

    def main(self):
        self.main_menu()
        self.ui.done()
Example #27
0
 def __init__(self):
     self.title = None
     self.txt = None
     self.ui = PiUi()
     self.pattern = None
 def __init__(self):
     self.title = None
     self.txt = None
     self.img = None
     self.ui = PiUi(img_dir=os.path.join(current_dir, 'imgs'))
     self.src = "chickens.png"
Example #29
0
from piui import PiUi

ui = PiUi()
page = ui.new_ui_page(title="Hello")
title = page.add_textbox("Hello, world!")
Example #30
0
#!/usr/bin/python

from piui import PiUi
 
ui = PiUi()
page = ui.new_ui_page(title="Hello")
title = page.add_textbox("Hello, world!")
Example #31
0
 def setUp(self):
     self._ui = PiUi("Test", timeout=1)
Example #32
0
class DemoPiUi(object):
    def __init__(self):
        self.title = None
        self.txt = None
        self.img = None
        self.img_dir = os.path.join(current_dir, 'imgs')
        self.thumbs_dir = os.path.join(current_dir, 'thumbs')
        self.ui = PiUi(self.thumbs_dir)
        self.src = "sunset.png"

    def page_static(self):
        self.page = self.ui.new_ui_page(title="Static Content",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.page.add_textbox("Add a mobile UI to your Raspberry Pi project",
                              "h1")
        self.page.add_element("hr")
        self.page.add_textbox(
            "You can use any static HTML element " +
            "in your UI and <b>regular</b> <i>HTML</i> <u>formatting</u>.",
            "p")
        self.page.add_element("hr")
        self.page.add_textbox(
            "Your python code can update page contents at any time.", "p")
        update = self.page.add_textbox("Like this...", "h2")
        time.sleep(2)
        for a in range(1, 5):
            update.set_text(str(a))
            time.sleep(1)

    def page_buttons(self):
        self.page = self.ui.new_ui_page(title="Buttons",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Buttons!", "h1")
        plus = self.page.add_button("Up Button &uarr;", self.onupclick)
        minus = self.page.add_button("Down Button &darr;", self.ondownclick)

    def page_input(self):
        self.page = self.ui.new_ui_page(title="Input",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.title = self.page.add_textbox("Input", "h1")
        self.txt = self.page.add_input("text", "Name")
        button = self.page.add_button("Say Hello", self.onhelloclick)

    def page_images(self):
        self.page = self.ui.new_ui_page(title="Images",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        takepic = self.page.add_button("Take Picture", self.takepicbutton)
        self.capturetext = self.page.add_textbox("")
        self.page.add_element('br')
        for root, _, files in os.walk(self.thumbs_dir):
            for f in files:
                self.page.add_image(f)

    def page_toggles(self):
        self.page = self.ui.new_ui_page(title="Toggles",
                                        prev_text="Back",
                                        onprevclick=self.main_menu)
        self.list = self.page.add_list()
        self.list.add_item("Lights",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle, "lights"))
        self.list.add_item("TV",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle, "tv"))
        self.list.add_item("Microwave",
                           chevron=False,
                           toggle=True,
                           ontoggle=functools.partial(self.ontoggle,
                                                      "microwave"))
        self.page.add_element("hr")
        self.title = self.page.add_textbox("Home Appliance Control", "h1")

    def page_console(self):
        con = self.ui.console(title="Console",
                              prev_text="Back",
                              onprevclick=self.main_menu)
        con.print_line("Hello Console!")

    def main_menu(self):
        self.page = self.ui.new_ui_page(title="PiUi")
        self.list = self.page.add_list()
        self.list.add_item("Static Content",
                           chevron=True,
                           onclick=self.page_static)
        self.list.add_item("Buttons", chevron=True, onclick=self.page_buttons)
        self.list.add_item("Input", chevron=True, onclick=self.page_input)
        self.list.add_item("Images", chevron=True, onclick=self.page_images)
        self.list.add_item("Toggles", chevron=True, onclick=self.page_toggles)
        self.list.add_item("Console!", chevron=True, onclick=self.page_console)
        self.ui.done()

    def main(self):
        self.main_menu()
        self.ui.done()

    def onupclick(self):
        self.title.set_text("Up ")
        print "Up"

    def ondownclick(self):
        self.title.set_text("Down")
        print "Down"

    def onhelloclick(self):
        print "onstartclick"
        self.title.set_text("Hello " + self.txt.get_text())
        print "Start"

    def takepicbutton(self):
        self.capturetext.set_text("wait...")
        picname = time.strftime("%Y%m%d_%H%M%S", time.gmtime())
        os.system("raspistill -t 0 -o " + self.img_dir + "/" + picname +
                  ".jpg")
        newPic = Image.open(self.img_dir + "/" + picname + ".jpg")
        newPreview = newPic.resize((280, 200), Image.NEAREST)
        newPreview.save(self.thumbs_dir + "/" + picname + ".jpg")
        self.capturetext.set_text("DONE")

    def ontoggle(self, what, value):
        self.title.set_text("Toggled " + what + " " + str(value))