def tags(self): """ The tags for this server. """ if not self._tags: self._tags = Tags(rsapi=self.rsapi) # Use current_instance_href if it is present, otherwise # use the normal server href. if self.current_instance_href: self._tags.for_resource(self.current_instance_href) else: self._tags.for_resource(self.href) #self._tags = current_tags return self._tags
def add_question(): mongoengine.connect('Words', host='mongodb://localhost/Words') if (not request.data) or (not 'tags' in request.data) or (not 'word' in request.data) or ( not 'answer' in request.data): abort(400) tagList = [] data = json.loads(request.get_data()) content = data['word'].encode('utf8') answer = data['answer'].encode('utf8') for index in data['tags']: #todo:gets_or_create getTag = Tags.objects(id=index['id']) if 0 == len(getTag): addedTag = Tags(name=index['name'].encode('utf8'), date=datetime.datetime.now).save() tagList.append(Tag(id=addedTag.id, name=addedTag.name, date=addedTag.date)) else: tagList.append(Tag(id=getTag[0].id, name=getTag[0].name, date=getTag[0].date)) questionItem = Question() questionItem.word = content questionItem.answer = answer questionItem.tags = tagList questionItem.save() js = Question.objects().to_json() resp = Response(js, status=200, mimetype='application/json', charset='utf-8') return resp
def tags(self): from Tags import Tags if not self._tags: self._tags = Tags(rsapi=self.rsapi) self._tags.for_resource(self.href) return self._tags
def getObject(self, tagstring="", setFunction4Tagstring=None): """ check whether labelname exists in the labels @param tagstring: example "important customer:kristof" @type tagstring: string """ return Tags(tagstring, setFunction4Tagstring)
def __init__(self): self.sta_if = WLAN(STA_IF) self.settings = Settings(state=b"%s" % State.CLOCK).load() self.credentials = Credentials().load() self.tags = Tags().load() self.wifi = WifiManager(b"%s-%s" % (PUBLIC_NAME, self.settings.net_id)) self.mdns = mDnsServer(PUBLIC_NAME.lower(), self.settings.net_id) self.mqtt = MqttManager(self.mdns, BROKER_NAME, self.settings.net_id, MQTT_TOPIC_NAME) routes = { b"/": b"./index.html", b"/index.html": b"./index.html", b"/scripts.js": b"./scripts.js", b"/style.css": b"./style.css", b"/favicon.ico": self.favicon, b"/connect": self.connect, b"/action/color": self.set_color, b"/action/clock/display": self.display_clock, b"/action/brightness": self.set_brightness, b"/action/scoreboard/display": self.display_scoreboard, b"/action/scoreboard/green/more": self.scoreboard_green_more, b"/action/scoreboard/green/less": self.scoreboard_green_less, b"/action/scoreboard/red/more": self.scoreboard_red_more, b"/action/scoreboard/red/less": self.scoreboard_red_less, b"/action/scoreboard/reset": self.scoreboard_reset, b"/settings/values": self.settings_values, b"/settings/net-id": self.settings_net_id, b"/settings/ssids": self.get_ssids, } self.http = HttpServer(routes) print("> HTTP server up and running") self.clock = Clock(self.settings.color) self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) self.loop.create_task(self.check_mqtt()) self.loop.create_task(self.send_state()) self.loop.run_forever() self.loop.close()
def getTagString(self, labels=None, tags=None): """ Return a valid tags string, it's recommended to use this function and not to build the script manually to skip reserved letters. @param labels: A set of labels @param tags: A dict with key values """ labels = labels or set() tags = tags or dict() if not isinstance(labels, set): raise TypeError("labels must be of type set") if not isinstance(tags, dict): raise TypeError("tags must be of type dict") t = Tags() t.labels = labels t.tags = tags return str(t)
def run(self): for i in range(5): message_text = fake.sentence(nb_words=15, variable_nb_words=True, ext_word_list=None) receiver = self.__users_list[random.randint( 0, self.__users_amount - 1)] self.__server.create_message(self.__user_id, receiver, message_text, Tags.get_random()) print("%s - done" % self.__user_id)
def add_tag(): mongoengine.connect('Words', host='mongodb://localhost/Words') if (not request.data) or (not 'name' in request.data): abort(400) data = json.loads(request.get_data()) name = data['name'].encode('utf8') tagItem = Tags(name=name) tagItem.save() js = { 'id': str(tagItem.id), 'name': tagItem.name } result = json.dumps(js) resp = Response(result, status=200, mimetype='application/json') return resp
def __get_users_with_tagged_messages_from_db(self, tags): session = self.__driver.session() tags = tags.split(", ") for tag in tags: if not Tags.has_member(tag): raise ValueError(f"Tag: {tag} doesnt exist") query = "MATCH (u:user)-[r:messages]-() WHERE" for tag in tags: query += f" '{tag}' IN r.tags AND" query = query[:-3] + "RETURN u" return session.run(query)
def __init__(self): self.sta_if = WLAN(STA_IF) self.settings = Settings().load() self.credentials = Credentials().load() self.tags = Tags().load() self.wifi = WifiManager(b"%s-%s" % (PUBLIC_NAME, self.settings.net_id)) self.mdns = mDnsServer(PUBLIC_NAME.lower(), self.settings.net_id) self.mqtt = MqttManager( self.mdns, BROKER_NAME, self.settings.net_id, MQTT_TOPIC_NAME ) routes = { b"/": b"./index.html", b"/index.html": b"./index.html", b"/scripts.js": b"./scripts.js", b"/style.css": b"./style.css", b"/favicon.ico": self.favicon, b"/connect": self.connect, b"/action/go-up": self.go_up, b"/action/go-down": self.go_down, b"/action/stop": self.stop, b"/settings/values": self.settings_values, b"/settings/net-id": self.settings_net_id, b"/settings/reverse-motor": self.reverse_motor, b"/settings/ssids": self.get_ssids, } self.http = HttpServer(routes) print("> HTTP server up and running") self.motor = Motor() self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) self.loop.create_task(self.check_mqtt()) self.loop.create_task(self.send_state()) self.loop.run_forever() self.loop.close()
def from_dict(cls, label_dict): if not isinstance(label_dict, dict): raise InvalidLabelFormatError(label_dict) if not (label_dict.get("available_tags") and label_dict.get("tags")): raise InvalidLabelFormatError(label_dict) available_tags = label_dict["available_tags"] tags = label_dict["tags"] if not (is_list_of_strings(available_tags) and is_list_of_strings(tags)): raise InvalidLabelFormatError(label_dict) tags_obj = Tags(available_tags) return cls(tags_obj, tags)
class Main: def __init__(self): self.sta_if = WLAN(STA_IF) self.settings = Settings(state=b"%s" % State.CLOCK).load() self.credentials = Credentials().load() self.tags = Tags().load() self.wifi = WifiManager(b"%s-%s" % (PUBLIC_NAME, self.settings.net_id)) self.mdns = mDnsServer(PUBLIC_NAME.lower(), self.settings.net_id) self.mqtt = MqttManager(self.mdns, BROKER_NAME, self.settings.net_id, MQTT_TOPIC_NAME) routes = { b"/": b"./index.html", b"/index.html": b"./index.html", b"/scripts.js": b"./scripts.js", b"/style.css": b"./style.css", b"/favicon.ico": self.favicon, b"/connect": self.connect, b"/action/color": self.set_color, b"/action/clock/display": self.display_clock, b"/action/brightness": self.set_brightness, b"/action/scoreboard/display": self.display_scoreboard, b"/action/scoreboard/green/more": self.scoreboard_green_more, b"/action/scoreboard/green/less": self.scoreboard_green_less, b"/action/scoreboard/red/more": self.scoreboard_red_more, b"/action/scoreboard/red/less": self.scoreboard_red_less, b"/action/scoreboard/reset": self.scoreboard_reset, b"/settings/values": self.settings_values, b"/settings/net-id": self.settings_net_id, b"/settings/ssids": self.get_ssids, } self.http = HttpServer(routes) print("> HTTP server up and running") self.clock = Clock(self.settings.color) self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) self.loop.create_task(self.check_mqtt()) self.loop.create_task(self.send_state()) self.loop.run_forever() self.loop.close() async def check_wifi(self): while True: self.clock.stop() self.clock.play_spinner(SPINNER_RATE, ORANGE) await sleep_ms(2000) while not self.sta_if.isconnected(): await sleep_ms(1000) self.clock.stop_effect_init = True if self.settings.state != b"%s" % State.OFF: self.settings.state = b"%s" % State.CLOCK self.settings.write() self.clock.display() else: self.clock.clear_all() while self.sta_if.isconnected(): await sleep_ms(1000) async def check_mqtt(self): while True: while self.mqtt.connected: self.check_message_mqtt() await sleep_ms(MQTT_CHECK_MESSAGE_INTERVAL) while not self.mqtt.connected: await sleep_ms(MQTT_CHECK_CONNECTED_INTERVAL) self.send_state_mqtt() def check_message_mqtt(self): try: message = self.mqtt.check_messages() if message: if match("add-tag/", message): tag = message.split(b"/")[1] self.tags.append(tag) elif match("remove-tag/", message): tag = message.split(b"/")[1] self.tags.remove(tag) except Exception as e: print("> Main.check_message_mqtt exception: {}".format(e)) def settings_values(self, params): essid = self.credentials.essid if not essid: essid = b"" if self.settings.state == b"%s" % State.OFF: l = 0 else: _, _, l = self.clock.hsl result = ( b'{"ip": "%s", "netId": "%s", "essid": "%s", "brightness": "%s"}' % (self.wifi.ip, self.settings.net_id, essid, int(l))) return result def favicon(self, params): print("> NOT sending the favico :-)") def connect(self, params): self.credentials.essid = params.get(b"essid", None) self.credentials.password = params.get(b"password", None) self.credentials.write() self.loop.create_task(self.wifi.connect()) def display_clock(self, params=None): if self.settings.state != b"%s" % State.CLOCK: self.settings.state = b"%s" % State.CLOCK self.settings.write() self.clock.display() def display_scoreboard(self, params=None): if self.settings.state != b"%s" % State.SCOREBOARD: self.clock.stop() self.settings.state = b"%s" % State.SCOREBOARD self.settings.write() self.clock.display_scoreboard() def set_color(self, params): self.display_clock() color = params.get(b"hex", None) if color: self.clock.set_color(color) self.settings.color = color self.settings.write() _, _, l = self.clock.hsl return b'{"brightness": "%s"}' % int(l) def scoreboard_green_more(self, params): self.scoreboard_update(Player.GREEN, 1) def scoreboard_green_less(self, params): self.scoreboard_update(Player.GREEN, -1) def scoreboard_red_more(self, params): self.scoreboard_update(Player.RED, 1) def scoreboard_red_less(self, params): self.scoreboard_update(Player.RED, -1) def scoreboard_update(self, player, increment): if player == Player.GREEN: self.clock.update_scoreboard_green(increment) else: self.clock.update_scoreboard_red(increment) self.display_scoreboard() def set_brightness(self, params): l = int(params.get(b"l", 0)) if l > 0: self.display_clock() self.clock.set_brightness(l) self.settings.color = b"%s" % self.clock.hex else: self.clock.off() self.settings.state = b"%s" % State.OFF self.settings.write() def scoreboard_reset(self, params): self.display_scoreboard() self.clock.reset_scoreboard() def settings_net_id(self, params): id = params.get(b"id", None) if id: self.settings.net_id = id self.settings.write() self.mdns.set_net_id(id) async def send_state(self): while True: self.send_state_mqtt() await sleep_ms(MQTT_STATUS_INTERVAL) def send_state_mqtt(self): try: tags = [] # for tag in self.tags.tags: # tags.append("\"%s\"" % (tag.decode('utf-8'))) # state = b'{"ip": "%s", "type": "%s", "state": "%s", "tags": [%s] }' % ( # self.wifi.ip, # DEVICE_TYPE, # State.STATE_TEXT[self.settings.state], # ",".join(tags) # ) # self.mqtt.publish_state(state) except Exception as e: print("> Main.send_state_mqtt exception: {}".format(e)) def get_ssids(self, params): return self.wifi.get_ssids()
tags_str = [ "red", "blue", "yellow", "yellow_2", "light_brown", "light_brown_2", "purple", "bronze", "orange" # "__white_" ] print("\n-- Tags --\n") tags_obj = Tags(tags_str) print(tags_obj) test_tags = ["red", "black", "white", "blue"] print() print("get_accepted(" + str(test_tags) + ") => " + str(tags_obj.get_accepted(test_tags))) print("\nget_rejected(" + str(test_tags) + ") => " + str(tags_obj.get_rejected(test_tags))) tags_file_path = data_folder + "tags.json" print("\nSaving tags to a file...") tags_obj.to_json_file(tags_file_path) print("\nReading tags from a file...\n") print(Tags.from_json_file(tags_file_path))
class Deployment(XMLModel): _nickname = None _description = None _created_at = None _updated_at = None _servers = list() _href = None def __str__(self): return "%s" % (self.nickname) @property def nickname(self): return self._nickname @nickname.setter @ElementTreeValueOK def nickname(self, value): self._nickname = value @property def description(self): return self._description @description.setter @ElementTreeValueOK def description(self, value): self._description = value @property def created_at(self): return self._created_at @created_at.setter @ElementTreeValueOK def created_at(self, value): self._created_at = value @property def updated_at(self): return self._updated_at @updated_at.setter @ElementTreeValueOK def updated_at(self, value): self._updated_at = value @property def servers(self): return self._servers @servers.setter def servers(self, value): from Server import Server if isinstance(value, XMLCLASS) and value.tag == "servers": self._servers = list() for element in value: self.servers.append(Server(element, self.rsapi)) # for element ... else: self._servers = value @property def href(self): return self._href @href.setter @ElementTreeValueOK def href(self, value): self._href = value @property def tags(self): from Tags import Tags if not self._tags: self._tags = Tags(rsapi=self.rsapi) self._tags.for_resource(self.href) return self._tags @tags.setter def tags(self, value): self.taint("tags") if isinstance(value, XMLCLASS) and value.tag == "tags": self._tags = list() for element in value: self.tags.append(Tag(element, self.rsapi)) # for element ... else: self._tags = value # def tags ELEMENTS = { "nickname": nickname, "updated-at": updated_at, "created-at": created_at, "description": description, "servers": servers, "href": href, "tags": tags, }
def __init__(self,master): self.master=master #load books from database self.booklist=self.get_booklist() #showlist is the book list shwon in the listbox self.showlist=copy.deepcopy(self.booklist) # selection of the listbox self._sel='' self._curSelNum=0 self._preSel='x' self._curID='' self._curBook='' self._allTags=self._getAllTags() #store all tags of all books print self._allTags ##layout components #FmLeft:left frame FmLeft=tk.Frame(master,width=400,height=500) FmLeft.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) FmLeft.grid_columnconfigure(0,weight=1) FmLeft.grid_rowconfigure(1,weight=1) #FmRight: right frame FmRight=tk.Frame(master,width=300,height=500) FmRight.grid(row=0,column=1,sticky=(tk.N,tk.S,tk.W,tk.E)) FmRight.grid_columnconfigure(0,weight=1) FmRight.grid_rowconfigure(0,weight=1) #make window resizable master.grid_columnconfigure(0,weight=2) master.grid_columnconfigure(1,weight=1) master.grid_rowconfigure(0,weight=1) #### to do #### # write some subclasses to layout this main window into modules ###################################Left Frame########################################### # set searchBar sBar=searchBar(FmLeft,self._allTags); sBar.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.E,tk.W)) sBar.sNameBtn['command']=self.searchName sBar.sNameEn.bind('<Return>',lambda event:(self.searchName())) sBar.sTagBtn['command']=self.searchTag sBar.sTagEn.bind('<Return>',lambda event:(self.searchTag())) ##scrollbar and listbox #FmLL: Listbox on the Left Frame FmLL=tk.Frame(FmLeft) FmLL.grid(row=1,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) FmLL.grid_columnconfigure(0,weight=1) FmLL.grid_rowconfigure(0,weight=1) sld=tk.Scrollbar(FmLL) lbx=tk.Listbox(FmLL) sld['command']=lbx.yview lbx['yscrollcommand']=sld.set lbx['width']=80 #for book in self.booklist: # lbx.insert(tk.END,book.path) #the default selection is set to 0, i.e., the first book #lbx.select_set(0) lbx.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) sld.grid(row=0,column=1,sticky=(tk.N,tk.S,tk.W,tk.E)) lbx.grid_rowconfigure(0, weight=1) sld.grid_rowconfigure(0, weight=1) #show total book number FmLE=tk.Frame(FmLeft) FmLE.grid(row=2,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) totalboks=tk.Label(FmLE,text='%d books in database.' % len(self.booklist)) totalboks.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W)) rv=tk.Button(FmLE,text='Reverse',command=self.reverse_order) rv.grid(row=0,column=2,sticky=(tk.N,tk.S,tk.E),pady=2) FmLE.grid_columnconfigure(1, weight=1) ####################################Right Frame############################################################# FmRR=tk.Frame(FmRight) FmRR.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) FmRR1=tk.Frame(FmRR) FmRR1.grid(row=0,column=0) ##show review score, drawed by canvas review=review_stars(FmRR1) rvCallbacks=map(self.setScore,list(range(5))) for i in range(5): review.stars[i].bind('<Button-1>',rvCallbacks[i]) #button to open the selected book read=tk.Button(FmRR,text='Read',command=self.open_callback) read.grid(row=0,column=3,sticky=(tk.N,tk.S,tk.E)) FmRR.grid_columnconfigure(1, weight=1) ##show tags FmRTags=tk.Frame(FmRight) FmRTags.grid(row=2,column=0,sticky=(tk.N,tk.S,tk.E,tk.W),pady=5) tags=Tags(FmRTags,'C Python') tags.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W)) tags.setTagEn.bind('<Return>',self.setTag) ##load a folder FmRLoad=tk.Frame(FmRight) FmRLoad.grid(row=3,column=0,sticky=(tk.N,tk.S,tk.W,tk.E),pady=5) #load books from a folder and save to database Lb1=tk.Label(FmRLoad,text='Load folder:') En3=tk.Entry(FmRLoad) Btn3=tk.Button(FmRLoad,text='Load',command=self.load_folder) Lb1.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) En3.grid(row=0,column=1,sticky=(tk.N,tk.S,tk.W,tk.E)) Btn3.grid(row=0,column=2,sticky=(tk.N,tk.S,tk.W,tk.E)) FmRLoad.grid_columnconfigure(1, weight=1) ##description desp=tk.Text(FmRight) desp.insert(tk.INSERT, '编程啊,快来呀...Hello, this is a book. sdflnklsdfnm,.sdfnmwepfjpcmwmfs.,dnc pi\n') desp.insert(tk.END,'Goodbye!') desp['width']=40 desp.grid(row=4,column=0,sticky=(tk.N,tk.S,tk.W,tk.E)) ##edit and submit description FmRSD=tk.Frame(FmRight) FmRSD.grid(row=5,column=0) Btn4=tk.Button(FmRSD,text='Submit edit',command=self.updateDescription) Btn4.grid(row=0,column=0,sticky=(tk.N,tk.S,tk.E,tk.W)) ####################The GUI layout is done!########################### self.FmLeft=FmLeft self.FmRight=FmRight self.lbx=lbx self.sld=sld self.review=review self.desp=desp self.submitDesp=Btn4 self.reverse=rv self.sBar=sBar self.tags=tags self.read=read self.EntryFolder=En3 self.totalbooks=totalboks # flag to restore search by name self.SNFlag=False self.STFlag=False # set default view self.set_default_display()
class Server(XMLModel): _nickname = None _href = None _state = None _created_at = None _current_instance_href = None _tags = list() _server_template = None _server_template_href = None _deployment = None _deployment_href = None # ServerSettings _settings = None def __str__(self): return "%s" % (self.nickname) @property def href(self): """ The href for this server """ return self._href @href.setter @ElementTreeValueOK def href(self, value): self._href = value @property def settings(self): """ The settings for this server, returns a ServerSettings object See also: 'sub-resources' on this API reference: http://support.rightscale.com/15-References/RightScale_API_Reference_Guide/02-Management/02-Servers""" if self._settings is None: self._settings = ServerSettings("%s/settings" % self._href, self.rsapi) return self._settings @settings.setter @ElementTreeValueOK def settings(self, value): self._settings = ServerSettings(value, self.rsapi) @property def server_template(self): """ The ServerTemplate for this server. """ if self._server_template is None: self.get_server_template return self._server_template def get_server_template(self): self._server_template = ServerTemplate(self.server_template_href, self.rsapi) # def get_server_template @server_template.setter @ElementTreeValueOK def server_template(self, value): # Defer loading ServerTemplate until it is requested. self._server_template_href = value @property def current_instance_href(self): """ The current instance href. """ return self._current_instance_href @current_instance_href.setter @ElementTreeValueOK def current_instance_href(self, value): self._current_instance_href = value @property def deployment_href(self): """ The deployment href """ return self._deployment_href @deployment_href.setter @ElementTreeValueOK def deployment_href(self, value): self._deployment_href = value @property def deployment(self): """ The Deployment object for this server """ assert self._deployment_href from Deployment import Deployment return Deployment(self._deployment_href, self.rsapi) @property def nickname(self): """ The server nickname according to RightScale. Displayed in the UI. """ return self._nickname @nickname.setter @ElementTreeValueOK def nickname(self, value): self.taint("nickname") self._nickname = value @property def tags(self): """ The tags for this server. """ if not self._tags: self._tags = Tags(rsapi=self.rsapi) # Use current_instance_href if it is present, otherwise # use the normal server href. if self.current_instance_href: self._tags.for_resource(self.current_instance_href) else: self._tags.for_resource(self.href) #self._tags = current_tags return self._tags @tags.setter def tags(self, value): self.taint("tags") #print "Setting tags for %s to %s" % (self, value) if isinstance(value, XMLCLASS) and value.tag == "tags": self._tags = list() for element in value: self.tags.append(Tag(element, self.rsapi)) # for element ... else: self._tags = value # def tags def run_script(self, script_id): """ Runs script on this Server. """ href = self.href + "/run_script" params = {'right_script': script_id} response, content = self.rsapi.request(href, params, method="POST") return Status(response.get('location'), self.rsapi) def save(self): """ Save any modifications made to this Server. Can save: - tags - nickname Saving tags will affect the current instance as well as the 'next' instance. """ if "tags" in self.tainted: self.rsapi.save_tags(self, self.tags) self.untaint("tags") if len(self.tainted) > 0: #print "Want to save: %s" % (",".join(self.tainted.keys())) params = { } if "nickname" in self.tainted: params["server[nickname]"] = self.nickname self.untaint("nickname") # add other features here... response, content = self.rsapi.request(self.href, params, method="PUT") if response["status"] != "204": raise InvalidResponse("Error while updating server %s: (code %s) %s" % (self.href, response["status"], content)) else: assert len(content) == 0, "RightScale API docs claim content from a server update request will be empty" # for url in ... # if len(self.tainted) > 0 # def save ELEMENTS = { "current-instance-href": current_instance_href, "href": href, "nickname": nickname, "server-template-href": server_template, "settings": settings, "deployment-href": deployment_href, # TODO(sissel): Implement these "updated-at": None, "created-at": None, "state": None, "server-type": None, # Ignore the 'tags' data as this data is for the 'next' server version, # not the current instance. "tags": None }
class Server(XMLModel): _nickname = None _href = None _state = None _updated_at = None _created_at = None _server_type = None _current_instance_href = None _tags = list() _server_template = None _server_template_href = None _deployment = None _deployment_href = None # ServerSettings _settings = None def __str__(self): return "%s" % (self.nickname) @property def href(self): """ The href for this server """ return self._href @href.setter @ElementTreeValueOK def href(self, value): self._href = value @property def settings(self): """ The settings for this server, returns a ServerSettings object See also: 'sub-resources' on this API reference: http://support.rightscale.com/15-References/RightScale_API_Reference_Guide/02-Management/02-Servers""" if self._settings is None: self._settings = ServerSettings("%s/settings" % self._href, self.rsapi) return self._settings @settings.setter @ElementTreeValueOK def settings(self, value): self._settings = ServerSettings(value, self.rsapi) @property def server_template(self): """ The ServerTemplate for this server. """ if self._server_template is None: self.get_server_template return self._server_template def get_server_template(self): self._server_template = ServerTemplate(self.server_template_href, self.rsapi) # def get_server_template @server_template.setter @ElementTreeValueOK def server_template(self, value): # Defer loading ServerTemplate until it is requested. self._server_template_href = value @property def current_instance_href(self): """ The current instance href. """ return self._current_instance_href @current_instance_href.setter @ElementTreeValueOK def current_instance_href(self, value): self._current_instance_href = value @property def deployment_href(self): """ The deployment href """ return self._deployment_href @deployment_href.setter @ElementTreeValueOK def deployment_href(self, value): self._deployment_href = value @property def deployment(self): """ The Deployment object for this server """ assert self._deployment_href from Deployment import Deployment return Deployment(self._deployment_href, self.rsapi) @property def nickname(self): """ The server nickname according to RightScale. Displayed in the UI. """ return self._nickname @nickname.setter @ElementTreeValueOK def nickname(self, value): self.taint("nickname") self._nickname = value @property def state(self): """ The server state (pending/booting/operational). """ return self._state @state.setter @ElementTreeValueOK def state(self, value): self._state = value @property def updated_at(self): """ `datetime.datetime` of last server update. """ return self._updated_at @updated_at.setter @ElementTreeValueOK def updated_at(self, value): self._updated_at = self._parse_datetime(value) @property def created_at(self): """ `datetime.datetime` of server creation. """ return self._created_at @created_at.setter @ElementTreeValueOK def created_at(self, value): self._created_at = self._parse_datetime(value) @property def server_type(self): """ Server type (e.g. "ec2"). """ return self._server_type @server_type.setter @ElementTreeValueOK def server_type(self, value): self._server_type = value @property def tags(self): """ The tags for this server. """ if not self._tags: self._tags = Tags(rsapi=self.rsapi) # Use current_instance_href if it is present, otherwise # use the normal server href. if self.current_instance_href: self._tags.for_resource(self.current_instance_href) else: self._tags.for_resource(self.href) #self._tags = current_tags return self._tags @tags.setter def tags(self, value): self.taint("tags") #print "Setting tags for %s to %s" % (self, value) if isinstance(value, XMLCLASS) and value.tag == "tags": self._tags = list() for element in value: self.tags.append(Tag(element, self.rsapi)) # for element ... else: self._tags = value # def tags def run_script(self, script_id, script_inputs=None): """ Runs script on this Server. Inputs to the script may be passed in ``script_inputs`` dictionary. """ # Build script href script_href = "https://my.rightscale.com/api/acct/%s/right_scripts/%s" % \ (self.rsapi.account, script_id) params = {'server[right_script_href]': script_href} # Prepare script inputs script_inputs = script_inputs or {} for param, value in script_inputs.items(): key = 'server[parameters][%s]' % param params[key] = 'text:%s' % value # Run script href = self.href + "/run_script" response, content = self.rsapi.request(href, body=params, method="POST") if 'location' not in response: raise ExecutionError(content) return Status(response.get('location'), self.rsapi) def save(self): """ Save any modifications made to this Server. Can save: - tags - nickname Saving tags will affect the current instance as well as the 'next' instance. """ if "tags" in self.tainted: self.rsapi.save_tags(self, self.tags) self.untaint("tags") if len(self.tainted) > 0: #print "Want to save: %s" % (",".join(self.tainted.keys())) params = { } if "nickname" in self.tainted: params["server[nickname]"] = self.nickname self.untaint("nickname") # add other features here... response, content = self.rsapi.request(self.href, params, method="PUT") if response["status"] != "204": raise InvalidResponse("Error while updating server %s: (code %s) %s" % (self.href, response["status"], content)) else: assert len(content) == 0, "RightScale API docs claim content from a server update request will be empty" # for url in ... # if len(self.tainted) > 0 # def save def _parse_datetime(self, datetime_str): """ Return `datetime.datetime` object, parsed from string in RightScale date/time format. """ return datetime.datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%SZ") ELEMENTS = { "current-instance-href": current_instance_href, "href": href, "nickname": nickname, "server-template-href": server_template, "settings": settings, "deployment-href": deployment_href, "state": state, "updated-at": updated_at, "created-at": created_at, "server-type": server_type, # Ignore the 'tags' data as this data is for the 'next' server version, # not the current instance. "tags": None }
class Server(XMLModel): _nickname = None _href = None _state = None _created_at = None _current_instance_href = None _tags = list() _server_template = None _server_template_href = None _deployment = None _deployment_href = None # ServerSettings _settings = None def __str__(self): return "%s" % (self.nickname) @property def href(self): """ The href for this server """ return self._href @href.setter @ElementTreeValueOK def href(self, value): self._href = value @property def settings(self): """ The settings for this server, returns a ServerSettings object See also: 'sub-resources' on this API reference: http://support.rightscale.com/15-References/RightScale_API_Reference_Guide/02-Management/02-Servers""" if self._settings is None: self._settings = ServerSettings("%s/settings" % self._href, self.rsapi) return self._settings @settings.setter @ElementTreeValueOK def settings(self, value): self._settings = ServerSettings(value, self.rsapi) @property def server_template(self): """ The ServerTemplate for this server. """ if self._server_template is None: self.get_server_template return self._server_template def get_server_template(self): self._server_template = ServerTemplate(self.server_template_href, self.rsapi) # def get_server_template @server_template.setter @ElementTreeValueOK def server_template(self, value): # Defer loading ServerTemplate until it is requested. self._server_template_href = value @property def current_instance_href(self): """ The current instance href. """ return self._current_instance_href @current_instance_href.setter @ElementTreeValueOK def current_instance_href(self, value): self._current_instance_href = value @property def deployment_href(self): """ The deployment href """ return self._deployment_href @deployment_href.setter @ElementTreeValueOK def deployment_href(self, value): self._deployment_href = value @property def deployment(self): """ The Deployment object for this server """ assert self._deployment_href from Deployment import Deployment return Deployment(self._deployment_href, self.rsapi) @property def nickname(self): """ The server nickname according to RightScale. Displayed in the UI. """ return self._nickname @nickname.setter @ElementTreeValueOK def nickname(self, value): self.taint("nickname") self._nickname = value @property def tags(self): """ The tags for this server. """ if not self._tags: self._tags = Tags(rsapi=self.rsapi) # Use current_instance_href if it is present, otherwise # use the normal server href. if self.current_instance_href: self._tags.for_resource(self.current_instance_href) else: self._tags.for_resource(self.href) #self._tags = current_tags return self._tags @tags.setter def tags(self, value): self.taint("tags") print "Setting tags for %s to %s" % (self, value) if isinstance(value, XMLCLASS) and value.tag == "tags": self._tags = list() for element in value: self.tags.append(Tag(element, self.rsapi)) # for element ... else: self._tags = value # def tags def save(self): """ Save any modifications made to this Server. Can save: - tags - nickname Saving tags will affect the current instance as well as the 'next' instance. """ if "tags" in self.tainted: self.rsapi.save_tags(self, self.tags) self.untaint("tags") if len(self.tainted) > 0: #print "Want to save: %s" % (",".join(self.tainted.keys())) params = {} if "nickname" in self.tainted: params["server[nickname]"] = self.nickname self.untaint("nickname") # add other features here... response, content = self.rsapi.request(self.href, params, method="PUT") if response["status"] != "204": raise InvalidResponse( "Error while updating server %s: (code %s) %s" % (self.href, response["status"], content)) else: assert len( content ) == 0, "RightScale API docs claim content from a server update request will be empty" # for url in ... # if len(self.tainted) > 0 # def save ELEMENTS = { "current-instance-href": current_instance_href, "href": href, "nickname": nickname, "server-template-href": server_template, "settings": settings, "deployment-href": deployment_href, # TODO(sissel): Implement these "updated-at": None, "created-at": None, "state": None, "server-type": None, # Ignore the 'tags' data as this data is for the 'next' server version, # not the current instance. "tags": None }
class Main: def __init__(self): self.sta_if = WLAN(STA_IF) self.settings = Settings().load() self.credentials = Credentials().load() self.tags = Tags().load() self.wifi = WifiManager(b"%s-%s" % (PUBLIC_NAME, self.settings.net_id)) self.mdns = mDnsServer(PUBLIC_NAME.lower(), self.settings.net_id) self.mqtt = MqttManager( self.mdns, BROKER_NAME, self.settings.net_id, MQTT_TOPIC_NAME ) routes = { b"/": b"./index.html", b"/index.html": b"./index.html", b"/scripts.js": b"./scripts.js", b"/style.css": b"./style.css", b"/favicon.ico": self.favicon, b"/connect": self.connect, b"/action/go-up": self.go_up, b"/action/go-down": self.go_down, b"/action/stop": self.stop, b"/settings/values": self.settings_values, b"/settings/net-id": self.settings_net_id, b"/settings/reverse-motor": self.reverse_motor, b"/settings/ssids": self.get_ssids, } self.http = HttpServer(routes) print("> HTTP server up and running") self.motor = Motor() self.loop = get_event_loop() self.loop.create_task(self.check_wifi()) self.loop.create_task(self.check_mqtt()) self.loop.create_task(self.send_state()) self.loop.run_forever() self.loop.close() async def check_wifi(self): while True: await sleep_ms(STARTUP_DELAY) while not self.sta_if.isconnected(): await sleep_ms(WIFI_CHECK_CONNECTED_INTERVAL) self.send_state_mqtt() while self.sta_if.isconnected(): await sleep_ms(WIFI_CHECK_CONNECTED_INTERVAL) async def check_mqtt(self): while True: while self.mqtt.connected: self.check_message_mqtt() if self.motor.check_stopped_by_ir_sensor(): self.send_state_mqtt() await sleep_ms(MQTT_CHECK_MESSAGE_INTERVAL) while not self.mqtt.connected: await sleep_ms(MQTT_CHECK_CONNECTED_INTERVAL) self.send_state_mqtt() def check_message_mqtt(self): try: message = self.mqtt.check_messages() if message: if match("add-tag/", message): tag = message.split(b"/")[1] self.tags.append(tag) elif match("remove-tag/", message): tag = message.split(b"/")[1] self.tags.remove(tag) elif message == b"up": self.go_up() elif message == b"down": self.go_down() elif message == b"stop": self.stop() except Exception as e: print("> Main.check_message_mqtt exception: {}".format(e)) def settings_values(self, params): essid = self.credentials.essid if not essid: essid = b"" result = ( b'{"ip": "%s", "netId": "%s", "motorReversed": "%s", "essid": "%s"}' % ( self.wifi.ip, self.settings.net_id, self.settings.motor_reversed, essid, ) ) return result def favicon(self, params): print("> NOT sending the favico :-)") def connect(self, params): self.credentials.essid = params.get(b"essid", None) self.credentials.password = params.get(b"password", None) self.credentials.write() self.loop.create_task(self.wifi.connect()) def go_up(self, params=None): self.motor.go_up() self.send_state_mqtt() def go_down(self, params=None): self.motor.go_down() self.send_state_mqtt() def stop(self, params=None): self.motor.stop() self.send_state_mqtt() def settings_net_id(self, params): id = params.get(b"id", None) if id: self.settings.net_id = id self.settings.write() self.mdns.set_net_id(id) self.wifi.set_ap_essid(b"%s-%s" % (PUBLIC_NAME, id)) self.mdns.set_net_id(id) self.mqtt.set_net_id(id) def reverse_motor(self, params): motor_reversed = self.settings.motor_reversed if motor_reversed == b"0": motor_reversed = b"1" else: motor_reversed = b"0" self.settings.motor_reversed = motor_reversed self.settings.write() self.motor.reverse_direction() def settings_net_id(self, params): id = params.get(b"id", None) if id: self.settings.net_id = id self.settings.write() self.mdns.set_net_id(id) async def send_state(self): while True: self.send_state_mqtt() await sleep_ms(MQTT_STATUS_INTERVAL) def send_state_mqtt(self): try: tags = [] for tag in self.tags.tags: tags.append("\"%s\"" % (tag.decode('utf-8'))) state = b'{"ip": "%s", "type": "%s", "state": "%s", "tags": [%s] }' % ( self.wifi.ip, DEVICE_TYPE, self.motor.get_state(), ",".join(tags) ) self.mqtt.publish_state(state) except Exception as e: print("> Main.send_state_mqtt exception: {}".format(e)) def get_ssids(self, params): return self.wifi.get_ssids()