27842ac9 by Barry

Fairly big rewrite to be more memory friendly.

1 parent 27c9cd56
1 import utils
2 from roomloader import RoomLoader
3
1 4
2 global_aliases = { 5 global_aliases = {
3 'n': 'north', 6 'n': 'north',
...@@ -7,10 +10,23 @@ global_aliases = { ...@@ -7,10 +10,23 @@ global_aliases = {
7 'u': 'up', 10 'u': 'up',
8 'd': 'down', 11 'd': 'down',
9 'l': 'look', 12 'l': 'look',
13 '\'': 'say',
10 } 14 }
11 15
16 roomloader = RoomLoader('rooms')
17
12 class CommandHandler(object): 18 class CommandHandler(object):
13 19
20
21 def alias(self, command):
22 if command in global_aliases:
23 return global_aliases[command]
24 if 'aliases' not in self.players[self.id]:
25 self.players[self.id]["aliases"] = {}
26 if command in self.players[self.id]["aliases"]:
27 return self.players[self.id]["aliases"][command]
28 return command
29
14 def tokenize_params(self): 30 def tokenize_params(self):
15 cleaned = self.params.lower().strip() 31 cleaned = self.params.lower().strip()
16 tokens = [] 32 tokens = []
...@@ -21,14 +37,15 @@ class CommandHandler(object): ...@@ -21,14 +37,15 @@ class CommandHandler(object):
21 self.tokens = tokens 37 self.tokens = tokens
22 38
23 def look(self): 39 def look(self):
40 room_name = self.players[self.id]["room"]
24 self.mud.send_message(self.id, "") 41 self.mud.send_message(self.id, "")
25 if len(self.tokens) > 0 and self.tokens[0] == 'at': 42 if len(self.tokens) > 0 and self.tokens[0] == 'at':
26 del self.tokens[0] 43 del self.tokens[0]
27 if len(self.tokens) == 0: 44 if len(self.tokens) == 0:
28 self.mud.send_message(self.id, self.room.get_description()) 45 self.mud.send_message(self.id, roomloader.get_description(room_name))
29 else: 46 else:
30 subject = self.tokens[0] 47 subject = self.tokens[0]
31 items = self.room.get_look_items() 48 items = roomloader.get_look_items(room_name)
32 for item in items: 49 for item in items:
33 if subject in item: 50 if subject in item:
34 self.mud.send_message(self.id, items[item]) 51 self.mud.send_message(self.id, items[item])
...@@ -51,7 +68,7 @@ class CommandHandler(object): ...@@ -51,7 +68,7 @@ class CommandHandler(object):
51 68
52 # send player a message containing the list of exits from this room 69 # send player a message containing the list of exits from this room
53 self.mud.send_message(self.id, "Exits are: {}".format( 70 self.mud.send_message(self.id, "Exits are: {}".format(
54 ", ".join(self.room.get_exits()))) 71 ", ".join(roomloader.get_exits(room_name))))
55 72
56 return True 73 return True
57 74
...@@ -69,7 +86,7 @@ class CommandHandler(object): ...@@ -69,7 +86,7 @@ class CommandHandler(object):
69 ex = self.params.lower().strip() 86 ex = self.params.lower().strip()
70 87
71 # if the specified exit is found in the room's exits list 88 # if the specified exit is found in the room's exits list
72 if ex in self.room.get_exits(): 89 if ex in roomloader.get_exits(self.players[self.id]["room"]):
73 # go through all the players in the game 90 # go through all the players in the game
74 for pid, pl in self.players.items(): 91 for pid, pl in self.players.items():
75 # if player is in the same room and isn't the player 92 # if player is in the same room and isn't the player
...@@ -82,13 +99,13 @@ class CommandHandler(object): ...@@ -82,13 +99,13 @@ class CommandHandler(object):
82 self.players[self.id]["name"], ex)) 99 self.players[self.id]["name"], ex))
83 100
84 # update the player's current room to the one the exit leads to 101 # update the player's current room to the one the exit leads to
85 loaded = self.load_room(self.room.get_exits()[ex]) 102
86 if loaded == None: 103 if roomloader.get_title(ex) == None:
87 self.mud.send_message(id, "An invisible force prevents you from going in that direction.") 104 self.mud.send_message(id, "An invisible force prevents you from going in that direction.")
88 return True 105 return True
89 else: 106 else:
90 self.players[self.id]["room"] = self.room.get_exits()[ex] 107 self.players[self.id]["room"] = roomloader.get_exits(self.players[self.id]["room"])[ex]
91 self.room = loaded 108 self.room = ex
92 109
93 # go through all the players in the game 110 # go through all the players in the game
94 for pid, pl in self.players.items(): 111 for pid, pl in self.players.items():
...@@ -103,41 +120,70 @@ class CommandHandler(object): ...@@ -103,41 +120,70 @@ class CommandHandler(object):
103 self.players[self.id]["name"], ex)) 120 self.players[self.id]["name"], ex))
104 121
105 # send the player a message telling them where they are now 122 # send the player a message telling them where they are now
106 self.mud.send_message(id, "You arrive at '{}'".format(self.room.get_title())) 123 self.mud.send_message(self.id, "You arrive at '{}'".format(roomloader.get_title(self.players[self.id]["room"])))
107 124 self.tokens = []
125 return self.look()
108 # the specified exit wasn't found in the current room 126 # the specified exit wasn't found in the current room
109 else: 127 else:
110 # send back an 'unknown exit' message 128 # send back an 'unknown exit' message
111 self.mud.send_message(id, "Unknown exit '{}'".format(ex)) 129 self.mud.send_message(id, "Unknown exit '{}'".format(ex))
112 return True 130 return True
113 131
132 def help(self):
133 if len(self.tokens) > 0:
134 filename = 'help/' + self.tokens[0] + '.txt'
135 else:
136 filename = 'help/help.txt'
137 try:
138 with open(filename, 'r', encoding='utf-8') as f:
139 for line in f:
140 self.mud.send_message(self.id, line, '\r')
141 self.mud.send_message(self.id, '')
142 except:
143 self.mud.send_message(self.id, 'No help topics available for \"{}\". A list\r\n of all commands is available at: help index'.format(self.tokens[0]))
144
145 def say(self):
146 # go through every player in the game
147 for pid, pl in self.players.items():
148 # if they're in the same room as the player
149 if self.players[pid]["room"] == self.players[self.id]["room"]:
150 # send them a message telling them what the player said
151 self.mud.send_message(pid, "{} says: {}".format(
152 self.players[self.id]["name"], self.params))
153 return True
154
155
156 def quit(self):
157 # send the player back the list of possible commands
158 self.mud.send_message(id, "Saving...")
159 utils.save_object_to_file(self.players[self.id], "players/{}.json".format(self.players[self.id]["name"]))
160 self.mud.disconnect_player(self.id)
161 return True
162
163 def save(self):
164 # send the player back the list of possible commands
165 self.mud.send_message(self.id, "Saving...")
166 utils.save_object_to_file(self.players[self.id], "players/{}.json".format(self.players[self.id]["name"]))
167 self.mud.send_message(self.id, "Save complete")
168 return True
114 169
115 def alias(self, command):
116 if command in global_aliases:
117 return global_aliases[command]
118 if 'aliases' not in self.players[self.id]:
119 self.players[self.id]["aliases"] = {}
120 if command in self.players[self.id]["aliases"]:
121 return self.players[self.id]["aliases"][command]
122 return command
123 170
124 def parse(self, id, cmd, params, room, mud, players, load_room): 171
172 def parse(self, id, cmd, params, mud, players):
125 self.id = id 173 self.id = id
126 self.params = params 174 self.params = params
127 self.tokenize_params() 175 self.tokenize_params()
128 self.room = room
129 self.mud = mud 176 self.mud = mud
130 self.players = players 177 self.players = players
131 self.load_room = load_room
132 self.cmd = self.alias(cmd) 178 self.cmd = self.alias(cmd)
133
134 try: 179 try:
135 if self.cmd in self.room.get_exits(): 180 if self.cmd in roomloader.get_exits(self.players[id]["room"]):
136 self.params = self.cmd + " " + self.params 181 self.params = self.cmd + " " + self.params
137 self.cmd = "go" 182 self.cmd = "go"
138 method = getattr(self, self.cmd) 183 method = getattr(self, self.cmd)
139 return method() 184 return method()
140 except AttributeError: 185 except AttributeError as e:
186 print(e)
141 mud.send_message(id, "Unknown command '{}'".format(self.cmd)) 187 mud.send_message(id, "Unknown command '{}'".format(self.cmd))
142 return False 188 return False
143 189
......
1 Command:
2 go
3
4 Usage:
5 go <exit>
6
7 Description:
8 The go command moves through the exit specified. Common exits are
9 north, south, east, west, up, and down. Normally the exits will
10 be shown when you 'look' but not always since there may be a
11 hidden exit.
12
13 You may also exit from an area by typing the direction name itself,
14 e.g. > north
...@@ -2,6 +2,10 @@ Commands: ...@@ -2,6 +2,10 @@ Commands:
2 say <message> - Says something out loud, e.g. 'say Hello' 2 say <message> - Says something out loud, e.g. 'say Hello'
3 look - Examines the surroundings, e.g. 'look' 3 look - Examines the surroundings, e.g. 'look'
4 go <exit> - Moves through the exit specified, e.g. 'go outside' 4 go <exit> - Moves through the exit specified, e.g. 'go outside'
5 <exit> - You can exclude the 'go' and just enter the exit.
5 who - Lists all players currently connected 6 who - Lists all players currently connected
6 save - Saves your character 7 save - Saves your character
7 quit - Saves your character then closes the connection
...\ No newline at end of file ...\ No newline at end of file
8 quit - Saves your character then closes the connection
9
10 For general help:
11 help index
...\ No newline at end of file ...\ No newline at end of file
......
1 Additional information can be learned about a command by passing a command: help <subject>
2
3 Help Topics:
4
5 aliases
6 go
7 look
8 quit
9 save
10 say
11 who
...@@ -22,19 +22,20 @@ author: Mark Frimston - mfrimston@gmail.com ...@@ -22,19 +22,20 @@ author: Mark Frimston - mfrimston@gmail.com
22 """ 22 """
23 23
24 import time 24 import time
25 # import datetime 25 import sys
26 #import io 26 if 'esp' in sys.platform:
27 import json 27 import gc
28 import machine 28 import machine
29 # import the MUD server class 29 # import the MUD server class
30 from mudserver import MudServer 30 from mudserver import MudServer
31 from commands import CommandHandler 31 from commandhandler import CommandHandler
32 from roomloader import RoomLoader
33 import utils
32 34
33 print('STARTING MUD\r\n\r\n\r\n') 35 print('STARTING MUD\r\n\r\n\r\n')
34 36
35 flash_button = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP) 37 if 'esp' in sys.platform:
36 38 flash_button = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
37 rooms = {}
38 39
39 # stores the players in the game 40 # stores the players in the game
40 players = {} 41 players = {}
...@@ -44,34 +45,7 @@ mud = MudServer() ...@@ -44,34 +45,7 @@ mud = MudServer()
44 45
45 cmd_handler = CommandHandler() 46 cmd_handler = CommandHandler()
46 47
47 def load_room(room_name): 48 roomloader = RoomLoader('rooms')
48 print("Loading room:" + room_name)
49 try:
50 if room_name in rooms:
51 return rooms[room_name]
52
53
54 module = __import__('rooms.' + room_name.lower())
55 room_module = getattr(module, room_name.lower())
56 room_class = getattr(room_module, room_name)
57 instance = room_class()
58 rooms[room_name] = instance
59
60 return instance
61 except Exception as e:
62 print(e)
63 return None
64
65 def save_object_to_file(obj, filename):
66 with open(filename, 'w', encoding='utf-8') as f:
67 f.write(json.dumps(obj))
68
69 def load_object_from_file(filename):
70 try:
71 with open(filename, 'r', encoding='utf-8') as f:
72 return json.loads(f.read())
73 except Exception:
74 return None
75 49
76 def prompt(pid): 50 def prompt(pid):
77 if "prompt" not in players[pid]: 51 if "prompt" not in players[pid]:
...@@ -80,20 +54,14 @@ def prompt(pid): ...@@ -80,20 +54,14 @@ def prompt(pid):
80 54
81 # main game loop. We loop forever (i.e. until the program is terminated) 55 # main game loop. We loop forever (i.e. until the program is terminated)
82 while True: 56 while True:
83 gc.collect() 57 if 'esp' in sys.platform:
84 if flash_button.value() == 0: 58 gc.collect()
85 break 59 if flash_button.value() == 0:
60 break
86 # pause for 1/5 of a second on each loop, so that we don't constantly 61 # pause for 1/5 of a second on each loop, so that we don't constantly
87 # use 100% CPU time 62 # use 100% CPU time
88 time.sleep(0.001) 63 time.sleep(0.001)
89 64
90 # TODO: Add some cache removal if older than X
91 # now = datetime.datetime.now()
92 # delta = now - datetime.timedelta(minutes = 2)
93 # for room in rooms:
94 # if room.created < delta:
95 # del rooms[room]
96
97 # 'update' must be called in the loop to keep the game running and give 65 # 'update' must be called in the loop to keep the game running and give
98 # us up-to-date information 66 # us up-to-date information
99 mud.update() 67 mud.update()
...@@ -101,8 +69,6 @@ while True: ...@@ -101,8 +69,6 @@ while True:
101 # go through any newly connected players 69 # go through any newly connected players
102 for id in mud.get_new_players(): 70 for id in mud.get_new_players():
103 71
104
105
106 # add the new player to the dictionary, noting that they've not been 72 # add the new player to the dictionary, noting that they've not been
107 # named yet. 73 # named yet.
108 # The dictionary key is the player's id number. We set their room to 74 # The dictionary key is the player's id number. We set their room to
...@@ -115,7 +81,9 @@ while True: ...@@ -115,7 +81,9 @@ while True:
115 "prompt": "> ", 81 "prompt": "> ",
116 "aliases": {}, 82 "aliases": {},
117 } 83 }
118 84 with open('welcome.txt', 'r', encoding='utf-8') as f:
85 for line in f:
86 mud.send_message(id, line, "\r")
119 # send the new player a prompt for their name 87 # send the new player a prompt for their name
120 mud.send_message(id, "What is your name?") 88 mud.send_message(id, "What is your name?")
121 89
...@@ -148,15 +116,13 @@ while True: ...@@ -148,15 +116,13 @@ while True:
148 if id not in players: 116 if id not in players:
149 continue 117 continue
150 118
151 if players[id]["room"]:
152 rm = load_room(players[id]["room"])
153 # if the player hasn't given their name yet, use this first command as 119 # if the player hasn't given their name yet, use this first command as
154 # their name and move them to the starting room. 120 # their name and move them to the starting room.
155 if players[id]["name"] is None: 121 if players[id]["name"] is None:
156 if command.strip() == '' or command is None: 122 if command.strip() == '' or command is None:
157 mud.send_message(id, "Invalid Name") 123 mud.send_message(id, "Invalid Name")
158 continue 124 continue
159 loaded_player = load_object_from_file("players/{}.json".format(command)) 125 loaded_player = utils.load_object_from_file("players/{}.json".format(command))
160 if loaded_player is None: 126 if loaded_player is None:
161 players[id]["name"] = command 127 players[id]["name"] = command
162 players[id]["room"] = "Tavern" 128 players[id]["room"] = "Tavern"
...@@ -175,53 +141,15 @@ while True: ...@@ -175,53 +141,15 @@ while True:
175 + "\r\nType 'help' for a list of commands. Have fun!\r\n\r\n") 141 + "\r\nType 'help' for a list of commands. Have fun!\r\n\r\n")
176 142
177 # send the new player the description of their current room 143 # send the new player the description of their current room
178 mud.send_message(id, load_room(players[id]["room"]).get_description()) 144 mud.send_message(id, roomloader.get_description(players[id]["room"]))
179
180 # each of the possible commands is handled below. Try adding new
181 # commands to the game!
182 145
183 # 'help' command
184 elif command == "help":
185
186 with open('help/help.txt', 'r', encoding='utf-8') as f:
187 for line in f:
188 mud.send_message(id, line, '\r')
189 mud.send_message(id, '')
190
191 # 'help' command
192 elif command == "quit":
193
194 # send the player back the list of possible commands
195 mud.send_message(id, "Saving...")
196 save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
197 mud.disconnect_player(id)
198
199 # 'help' command
200 elif command == "save":
201
202 # send the player back the list of possible commands
203 mud.send_message(id, "Saving...")
204 save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
205 mud.send_message(id, "Save complete")
206
207 # 'say' command
208 elif command == "say":
209
210 # go through every player in the game
211 for pid, pl in players.items():
212 # if they're in the same room as the player
213 if players[pid]["room"] == players[id]["room"]:
214 # send them a message telling them what the player said
215 mud.send_message(pid, "{} says: {}".format(
216 players[id]["name"], params))
217
218 # 'look' command
219 else: 146 else:
220 147
221 handler_results = cmd_handler.parse(id, command, params, rm, mud, players, load_room) 148 handler_results = cmd_handler.parse(id, command, params, mud, players)
222 149
223 prompt(id) 150 prompt(id)
224 151
225 # Start WIFI Setup 152 # Start WIFI Setup
226 if flash_button.value() == 0:
227 import wifiweb
...\ No newline at end of file ...\ No newline at end of file
153 if 'esp' in sys.platform:
154 if flash_button.value() == 0:
155 import wifiweb
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -301,7 +301,7 @@ class MudServer(object): ...@@ -301,7 +301,7 @@ class MudServer(object):
301 301
302 try: 302 try:
303 # read data from the socket, using a max length of 4096 303 # read data from the socket, using a max length of 4096
304 data = cl.socket.recv(4096).decode("latin1") 304 data = cl.socket.recv(1024).decode("latin1")
305 305
306 # process the data, stripping out any special Telnet commands 306 # process the data, stripping out any special Telnet commands
307 message = self._process_sent_data(cl, data) 307 message = self._process_sent_data(cl, data)
......
1 {"name": "test", "room": "Room001", "inventory": null, "prompt": "> "}
...\ No newline at end of file ...\ No newline at end of file
1 {"name": "test", "room": "Tavern", "inventory": {}, "prompt": "> ", "aliases": {}}
...\ No newline at end of file ...\ No newline at end of file
......
1
2 import os
3 import json
4
5 class RoomLoader(object):
6
7 def __init__(self, directory):
8 self.directory = directory
9
10 def _get_room_file(self, room_name):
11 try:
12 filename = os.path.join(self.directory, room_name) + ".txt"
13 with open(filename, 'r', encoding='utf-8') as f:
14 return json.loads(f.read())
15 except Exception as e:
16 print("Error opening room file: {} with exception: {}".format(room_name, e))
17 return {"title": "", "description": "", "exits": {}, "look_items": {}}
18
19 def get_title(self, room_name):
20 return self._get_room_file(room_name)['title']
21
22 def get_description(self, room_name):
23 desc = self._get_room_file(room_name)['description']
24 chunks, chunk_size = len(desc), 80 #len(x)/4
25 lines = [ desc[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
26 return '\r\n'.join(lines)
27
28 def get_exits(self, room_name):
29 return self._get_room_file(room_name)['exits']
30
31 def get_look_items(self, room_name):
32 return self._get_room_file(room_name)['look_items']
File mode changed
1
2 # import datetime
3
4 class BaseRoom(object):
5
6 def __init__(self, title, description, exits, look_items):
7 self.title = title
8 self.description = description
9 self.exits = exits
10 self.look_items = look_items
11 # self.created = datetime.datetime.now()
12
13 def get_title(self):
14 return self.title
15
16 def get_description(self):
17 return self.description
18
19 def get_exits(self):
20 return self.exits
21
22 def get_look_items(self):
23 return self.look_items
1 from .baseroom import BaseRoom
2
3 class Outside(BaseRoom):
4
5 def __init__(self):
6
7 title = "Outside the Tavern"
8 description = "You are standing outside of a simple tavern made of pressed clay and shale roof. \r\nThe door becons you to come in and have a drink."
9 exits = {"tavern": "Tavern"}
10 look_items = {
11 "tavern": "A roughly constructed building.",
12 }
13
14 super(Outside, self).__init__(title, description, exits, look_items)
1 {
2 "title": "Outside the Tavern",
3 "description": "You are standing outside of a simple tavern made of pressed clay and shale roof. The door becons you to come in and have a drink.",
4 "exits": {"tavern": "Tavern"},
5 "look_items": {
6 "tavern": "A roughly constructed building."
7 }
8 }
...\ No newline at end of file ...\ No newline at end of file
1 from .baseroom import BaseRoom
2
3 class Room001(BaseRoom):
4
5 def __init__(self):
6
7 title = "Behind the bar"
8 description = "The back of the bar gives a full view of the tavern. The bar\r\n top is a large wooden plank thrown across some barrels."
9 exits = {"tavern": "Tavern"}
10 look_items = {
11 "bar": "The bar is a long wooden plank thrown over roughly hewn barrels.",
12 "barrel,barrels": "The old barrels bands are thick with oxidation and stained\r\n with the purple of spilled wine.",
13 "wooden,oak,plank": "An old solid oak plank that has a large number of chips\r\n and drink marks."
14 }
15
16 super(Room001, self).__init__(title, description, exits, look_items)
1 {
2 "title": "Behind the bar",
3 "description": "The back of the bar gives a full view of the tavern. The bar\r\n top is a large wooden plank thrown across some barrels.",
4 "exits": {"tavern": "Tavern"},
5 "look_items": {
6 "bar": "The bar is a long wooden plank thrown over roughly hewn barrels.",
7 "barrel,barrels": "The old barrels bands are thick with oxidation and stained\r\n with the purple of spilled wine.",
8 "wooden,oak,plank": "An old solid oak plank that has a large number of chips\r\n and drink marks."
9 }
10 }
1 from .baseroom import BaseRoom 1 {
2 2 "title": "Tavern",
3 class Tavern(BaseRoom): 3 "description": "You're in a cozy tavern warmed by an open fire.",
4 4 "exits": {"outside": "Outside", "behind bar": "Room001"},
5 def __init__(self): 5 "look_items": {
6
7 title = "Tavern"
8 description = "You're in a cozy tavern warmed by an open fire."
9 exits = {"outside": "Outside", "behind bar": "Room001"}
10 look_items = {
11 "bar": "The bar is a long wooden plank thrown over roughly hewn barrels.", 6 "bar": "The bar is a long wooden plank thrown over roughly hewn barrels.",
12 "barrel,barrels": "The old barrels bands are thick with oxidation and stained\r\n with the purple of spilled wine.", 7 "barrel,barrels": "The old barrels bands are thick with oxidation and stained\r\n with the purple of spilled wine.",
13 "wooden,oak,plank": "An old solid oak plank that has a large number of chips\r\n and drink marks.", 8 "wooden,oak,plank": "An old solid oak plank that has a large number of chips\r\n and drink marks.",
14 "fire": "The fire crackles quietly in the corner providing a small amount of light and heat." 9 "fire": "The fire crackles quietly in the corner providing a small amount of light and heat."
15 } 10 }
16 11 }
17 super(Tavern, self).__init__(title, description, exits, look_items)
...\ No newline at end of file ...\ No newline at end of file
......
1 {"test": "value"}
...\ No newline at end of file ...\ No newline at end of file
1 import json
2
3 def save_object_to_file(self, obj, filename):
4 with open(filename, 'w', encoding='utf-8') as f:
5 f.write(json.dumps(obj))
6
7 def save_object_to_file(obj, filename):
8 with open(filename, 'w', encoding='utf-8') as f:
9 f.write(json.dumps(obj))
10
11 def load_object_from_file(filename):
12 try:
13 with open(filename, 'r', encoding='utf-8') as f:
14 return json.loads(f.read())
15 except Exception:
16 return None
1 , \ / ,
2 / \ )\__/( / \
3 / \ (_\ /_) / \
4 ____/_____\__\@ @/___/_____\____
5 | |\../| |
6 | \VV/ |
7 | ----=WeeMud=---- |
8 |_________________________________|
9 | /\ / \\ \ /\ |
10 | / V )) V \ |
11 |/ ` // ' \|
12 ` V '
13
14 This mud is running on an ESP8266 chip
15 over a wireless connection to the internet.
16 It is standalone and 100% contained in 4mb
17 of flash and 256k of RAM. Please explore
18 and try to conquer the realm.
19
...@@ -40,32 +40,34 @@ class DNSQuery: ...@@ -40,32 +40,34 @@ class DNSQuery:
40 def accept_conn(listen_sock): 40 def accept_conn(listen_sock):
41 cl, addr = listen_sock.accept() 41 cl, addr = listen_sock.accept()
42 print('client connected from', addr) 42 print('client connected from', addr)
43 print('Request:')
44 request = cl.recv(2048) 43 request = cl.recv(2048)
45 print(request)
46 if 'GET /?' in request: 44 if 'GET /?' in request:
47 #GET /?network=Volley&networkpass=test
48 request = str(request) 45 request = str(request)
49 part = request.split(' ')[1] 46 part = request.split(' ')[1]
50 params = part.split('?')[1].split('&') 47 params = part.split('?')[1].split('&')
51 network_param = params[0].split('=')[1] 48 network_param = params[0].split('=')[1]
52 network_pass_param = params[1].split('=')[1] 49 network_pass_param = params[1].split('=')[1]
53 50
51 print("Setting network to: {}".format(network_param))
52
54 sta_if = network.WLAN(network.STA_IF) 53 sta_if = network.WLAN(network.STA_IF)
55 sta_if.active(True) 54 sta_if.active(True)
56 sta_if.connect(network_param, network_pass_param) 55 sta_if.connect(network_param, network_pass_param)
57 while sta_if.isconnected() == False: 56 while sta_if.isconnected() == False:
58 time.sleep(1) 57 time.sleep(1)
58
59 cl.send('<html><body>Configuration Saved!<br><br>Network: {} <br>IP Address: {}<br>Password: {}<br><br><br>Restarting Device...</body></html>'.format(network_param, sta_if.ifconfig()[0], network_pass_param)) 59 cl.send('<html><body>Configuration Saved!<br><br>Network: {} <br>IP Address: {}<br>Password: {}<br><br><br>Restarting Device...</body></html>'.format(network_param, sta_if.ifconfig()[0], network_pass_param))
60 cl.close() 60 cl.close()
61 time.sleep(20) 61 time.sleep(20)
62 machine.reset() 62 machine.reset()
63 return 63 return
64
64 print('Getting Network STA_IF') 65 print('Getting Network STA_IF')
65 sta_if = network.WLAN(network.STA_IF) 66 sta_if = network.WLAN(network.STA_IF)
66 print('Starting Network Scan...') 67 print('Starting Network Scan...')
67 avail_networks = sta_if.scan() 68 avail_networks = sta_if.scan()
68 print('Network Scan Complete') 69 print('Network Scan Complete')
70
69 endpoint_string = "" 71 endpoint_string = ""
70 for endpoint in avail_networks: 72 for endpoint in avail_networks:
71 endpoint_string += "<option value={}>{}</option>".format(endpoint[0].decode('latin1'), endpoint[0].decode('latin1')) 73 endpoint_string += "<option value={}>{}</option>".format(endpoint[0].decode('latin1'), endpoint[0].decode('latin1'))
...@@ -86,11 +88,8 @@ def accept_conn(listen_sock): ...@@ -86,11 +88,8 @@ def accept_conn(listen_sock):
86 </body> 88 </body>
87 </html> 89 </html>
88 \n\n""".format(endpoint_string) 90 \n\n""".format(endpoint_string)
89 # rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins] 91
90 # response = html % '\n'.join(rows)
91 print('Sending Response')
92 cl.send(response) 92 cl.send(response)
93 print('Closing Socket')
94 time.sleep(0.001) 93 time.sleep(0.001)
95 cl.close() 94 cl.close()
96 95
......