def startResource(self, resourceId): "Start resources by id. Possible to add new handlers for new resources such as sensors" if resourceId == "humidity_temperature_sensor": name = "humidity_temperature_sensor1" mySensor = SensorReader(name, "humidity_temperature_sensor") mySensor.start() self.runningResources[resourceId] = mySensor return Msg("Resource " + name + " started").info() elif resourceId == "motion_sensor": name = "motion_sensor1" mySensor = SensorReader(name, "motion_sensor") mySensor.start() self.runningResources[resourceId] = mySensor return Msg("Resource " + name + " started").info() elif resourceId == "button_sensor": name = "button_sensor1" mySensor = SensorReader(name, "button_sensor") mySensor.start() self.runningResources[resourceId] = mySensor return Msg("Resource " + name + " started").info() elif resourceId == "stereo": name = "stereo1" mySensor = SensorReader(name, "stereo") mySensor.start() self.runningResources[resourceId] = mySensor return Msg("Resource " + name + " started").info() else: Msg("Resource " + name + " not available").error()
def stopResource(self, resourceId): "Stop resource by id" # stop thread self.runningResources[resourceId].stop() # delete element from dictionary del self.runningResources[resourceId] return Msg("Stopped resource " + resourceId).info()
def get_messages(self): if not self.initialized: self.error_message = 'Cannot get messages for non initialized Bot' return [] messages = [] updates = self.bot.get_updates(offset=self.last_update_id).wait() for update in updates: # always increase last_update_id to get only new messages next time self.last_update_id = update.update_id + 1 self.chat_id = update.message.chat.id # skip all types of message except Message if not update.message or not isinstance(update.message, Message): continue m = Msg() ok = m.init(update) if not ok: self.errors[update.message.text] = m.get_error_message() continue messages.append(m) return messages
def PUT(self, *uri, **params): if len(uri) == 1: if uri[0] == "updateLightState": body = json.loads(cherrypy.request.body.read()) divisionName = body["divisionName"] lightName = body["lightName"] hc = HomeConfigurator(self.homeConfig) status = hc.updateLightState(divisionName, lightName) if status: return Msg("Updated " + lightName + " light state from " + divisionName + " division").info() else: return Msg("Could not update light state").error() else: return Msg("Invalid uri").error() else: return Msg("Invalid number of uris").error()
def getDevices(self, bot, update): try: r = requests.get(self.endpoint + '/devices') except requests.exceptions.RequestException as e: error = Msg("Unable to get devices").error() print e print error else: update.message.reply_text(r.text)
def getInfo(self, bot, update): try: r = requests.get(self.endpoint + "/home") except requests.exceptions.RequestException as e: error = Msg("Unable to get info").error() print e print error else: update.message.reply_text(r.text)
def addDivison(self, bot, update, args): try: r = requests.post(self.endpoint + '/addDivision', data=args[0]) except requests.exceptions.RequestException as e: error = Msg("Unable to get resources").error() print e print error else: update.message.reply_text(r.text)
def establish_connection(self): """Add a handshake and bitfield message to the queue of messages to be sent. Requires this peer to be associated with a torrent.""" assert self.atorrent self.add_message(self.atorrent.handshake()) bitfield = self.atorrent.strategy.get_bitfield() self.add_message(Msg('bitfield', bitfield=bitfield))
def listen(self): poll = zmq.Poller() poll.register(self._socket, zmq.POLLIN) while True: sockets = dict(poll.poll(1000)) if self._socket in sockets: msg = Pack.unpack_resp(self._socket.recv()) print('Client %s received: %s' % (self._identity, msg)) self._xmpp.event("zmq", Msg.fromZero(msg))
def removeDivision(self, bot, update): try: r = requests.delete(self.endpoint + '/removeDivision?divisionName=' + args[0]) except requests.exceptions.RequestException as e: error = Msg("Unable to get resources").error() print e print error else: update.message.reply_text(r.text)
def finish(self): assert self.strategy.has_all_pieces() log.info("torrent '%s' complete" % self.filename) # Update state for tracker announce self.event = 'completed' self.left = 0 for peer in self.peers: peer.add_message(Msg('not_interested'))
def updateLightState(self, bot, update, args): sendData = json.dumps({"divisionName": args[0], "lightName": args[1]}) try: r = requests.put(self.endpoint + '/updateLightState', data=sendData) except requests.exceptions.RequestException as e: error = Msg("Unable to get resources").error() print e print error else: update.message.reply_text(r.text)
def getBroker(self): "Get broker from catalog" try: r = requests.get(self.catalogEndpoint + '/broker') except requests.exceptions.RequestException as e: error = Msg("Unable to get broket").error() print e print error return error else: print "Requested broker, received: " + r.text return r.text
def newDevice(self, bot, update, args): device = json.dumps({"endpoint": args[0], "resources": args[1]}) try: r = requests.post(self.endpoint + '/addDevice', data=device) except requests.exceptions.RequestException as e: error = Msg("Unable to create new device").error() print e print error else: update.message.reply_text( "New device added! Your smart home said:") update.message.reply_text(r.text)
def getResources(self, bot, update, args): try: if self.tempId is not None: r = requests.get(self.endpoint + '/resources?id=' + self.tempId) else: r = requests.get(self.endpoint + '/resources?id=' + args[0]) except requests.exceptions.RequestException as e: error = Msg("Unable to get resources").error() print e print error else: update.message.reply_text(r.text)
def rebootDevice(self, bot, update, args): try: if self.tempId is not None: r = requests.get(self.endpoint + '/device?id=' + self.tempId) else: r = requests.get(self.endpoint + '/device?id=' + args[0]) device = json.loads(r.text)["info"] r = requests.get(device["endPoints"] + '/reboot') except requests.exceptions.RequestException as e: error = Msg("Unable to reboot device").error() print e print error else: update.message.reply_text(r.text)
def registerDevice(self): "Register device to catalog" print "Registering device..." device = None if os.path.exists(self.filePath): print "Read device from persistence..." jsonData = open(self.filePath).read() jsonData = json.loads(jsonData) device = jsonData["device"] device["timeStamp"] = str(datetime.datetime.now()) device = json.dumps(device) else: device = json.dumps({ "endPoints": self.endpoint, "resources": self.resources }) try: r = requests.post(self.catalogEndpoint + '/addDevice', data=device) except requests.exceptions.RequestException as e: error = Msg("unable to register").error() print e print error return error else: info = json.loads(r.text)["info"] deviceInfo = info["device"] if not os.path.exists(self.filePath): with open(self.filePath, "a+") as outfile: json.dump(deviceInfo, outfile) outfile.close() print "created deviceConfiguration.json" return Msg("New device registered.").info() else: return Msg("Device already registered.").info()
def setId(self, bot, update, args): try: if not os.path.exists(self.filePath): update.message.reply_text("Missing botConfiguration.json") else: jsonData = open(self.filePath).read() updateData = json.loads(jsonData) updateData["id"] = args[0] self.getId() except requests.exceptions.RequestException as e: error = Msg("Unable to set device id").error() print e print error else: update.message.reply_text(r.text)
def _have_or_bitfield(self, msg): if msg.kind == 'bitfield': byte_field = [ord(b) for b in msg.bitfield] for byte_idx, byte in enumerate(byte_field): # Most significant bit corresponds to smaller piece index for i in reversed(range(8)): has_piece = (byte >> i) & 1 if has_piece: self.pieces.add(byte_idx * 8 + (7-i)) log.info('peer has pieces ' + str(self.pieces)) else: self.pieces.add(msg.index) strat_interested = self.atorrent.strategy.am_interested(self) if not self.am_interested and strat_interested: self.add_message(Msg('interested')) return if not self.peer_choking and self.am_interested and strat_interested: self.prepare_next_request()
def handleResource(self, bot, update, args): try: if self.tempId is not None: r = requests.get(self.endpoint + '/device?id=' + self.tempId) else: r = requests.get(self.endpoint + '/device?id=' + args[0]) update.message.reply_text("DEVICE:") update.message.reply_text(r.text) device = json.loads(r.text)["info"] if self.tempId is not None: r = requests.get(device["endPoints"] + '/resource?id=' + args[0]) else: r = requests.get(device["endPoints"] + '/resource?id=' + args[1]) except requests.exceptions.RequestException as e: error = Msg("Unable to start resource").error() print e print error else: update.message.reply_text(r.text)
def get_next_request(self, peer): relevant_pieces = peer.pieces.intersection(self.wants_pieces) if relevant_pieces: piece_num_to_fetch = relevant_pieces.pop() else: if len(self.wants_pieces) < REQ_THRESHOLD: piece_num_to_fetch = self.wants_pieces.pop() self.wants_pieces.add(piece_num_to_fetch) else: return [] piece = self.atorrent.pieces[piece_num_to_fetch] assert not piece.full, 'Set logic is broken' msgs = [ Msg('request', index=piece_num_to_fetch, begin=begin, length=length) for begin, length in piece.empty_blocks() ] return msgs
def GET(self, *uri, **params): if len(uri) == 0: return Msg("Raspberry device").info() elif len(uri) == 1: if uri[0] == "resource": resourceId = params["id"] if resourceId in self.resources: if "info" in self.myDevice: if resourceId in self.runningResources: return self.stopResource(resourceId) else: return self.startResource(resourceId) else: return Msg("Not registered").error() else: return Msg("Resource not available").error() elif uri[0] == "reboot": self.myDevice = self.registerDevice() return Msg("Device rebooted").info() else: return Msg("Invalid uri").error() else: return Msg("Invalid number of uris").error()
def DELETE(self, *uri, **params): if len(uri) == 1: if uri[0] == "removeDivision": divisionName = params["divisionName"] hc = HomeConfigurator(self.homeConfig) status = hc.removeDivision(divisionName) if status: return Msg("Removed " + divisionName + " division").info() else: return Msg("Could not remove divisison").error() elif uri[0] == "removeLight": divisionName = params["divisionName"] lightName = params["lightName"] hc = HomeConfigurator(self.homeConfig) status = hc.removeLight(divisionName, lightName) if status: return Msg("Removed " + lightName + " light from " + divisionName + " division").info() else: return Msg("Could not remove light").error() else: return Msg("Invalid uri").error() else: return Msg("Invalid number of uris").error()
def broadcast_have(self, piece_index, exclude=None): for peer in self.peers: if not exclude == peer: peer.add_message(Msg('have', index=piece_index))
def test_parse_keep_alive(self): (messages, buf) = Msg.get_messages_from_buffer('\x00\x00\x00\x00') self.assertEqual(messages[0].msg_name, 'keep_alive')
def test_choke_to_buffer_and_back(self): choke = ChokeMsg() choke_buf = choke.get_buffer_from_message() self.assertEqual(choke_buf, Msg.get_messages_from_buffer(choke_buf)[0][0].get_buffer_from_message())
def test_parse_choke_from_buffer(self): (msgs, buf) = Msg.get_messages_from_buffer('\x00\x00\x00\x01\x00') self.assertEqual(msgs[0].msg_name, 'choke')
def test_parse_keep_alive_extra_bytes(self): (messages, buf) = Msg.get_messages_from_buffer('\x00\x00\x00\x00\x01') self.assertEqual(buf, '\x01')
timestep = setup.config("timestep") buf = setup.config("buffer") events = setup.config("events") pickled = setup.config("pickled") != 0 comm = setup.comm rank = comm.Get_rank() size = comm.Get_size() out = setup.publishMessageOutput("out") out.map(maxBuffered=buf, pickled=pickled) eventgen = (i * stoptime / events for i in range(events) if i % size == rank) steps = groupby(eventgen, lambda t: int(t/timestep)) def step(): return next(steps, (None, None)) runtime = setup.runtime(timestep) times = takewhile(lambda t: t < stoptime, runtime) nextStep, nextEvents = step() for t in times: if int(t/timestep) != nextStep: continue for when in nextEvents: msg = Msg(rank, nextStep, t, when) if not pickled: msg = str(msg) out.insertMessage(when, msg) nextStep, nextEvents = step()
def GET(self, *uri, **params): if len(uri) == 0: return json.dumps({"info": "Smart Home"}) elif len(uri) == 1: if uri[0] == "broker": jsonData = open(self.filePath).read() address = json.loads(jsonData)["broker"] return Msg(address).info() elif uri[0] == "devices": jsonData = open(self.filePath).read() devices = json.loads(jsonData)["devices"] return Msg({"devices": devices}).info() elif uri[0] == "users": jsonData = open(self.filePath).read() users = json.loads(jsonData)["users"] return Msg({"users": users}).info() elif uri[0] == "resources": deviceId = str(params["id"]) jsonData = open(self.filePath).read() devices = json.loads(jsonData)["devices"] for device in devices: if device["id"] == deviceId: resourcesToPrint = "" for resource in device["resources"]: if resourcesToPrint == "": resourcesToPrint += resource else: resourcesToPrint += ", " + resource return Msg({ "resources": "[" + resourcesToPrint + "]" }).info() return Msg("Resource not available").error() elif uri[0] == "device": deviceId = params["id"] # read from config file jsonData = open(self.filePath).read() devices = json.loads(jsonData)["devices"] for device in devices: if device["id"] == deviceId: return Msg(device).info() return Msg("No device with id=" + deviceId).error() elif uri[0] == "user": userId = params["id"] # read from config file jsonData = open(self.filePath).read() users = json.loads(jsonData)["users"] for user in users: if user["id"] == userId: return Msg(user).info() return Msg("No user with id=" + deviceId).error() elif uri[0] == "home": jsonData = open(self.homeConfig).read() return jsonData elif uri[0] == "beacons": jsonData = open(self.homeConfig).read() beacons = json.loads(jsonData)["beacons"] return json.dumps(beacons) else: return Msg("Invalid uri").error() else: return Msg("Invalid number of uris").error()
# -*- coding: utf-8 -*- from message import Msg msg = Msg() msg.buy_fund('sh000001') msg.send_markdown('养鸡')
def POST(self, *uri, **params): if len(uri) == 1: if uri[0] == "addDevice": # read body body = json.loads(cherrypy.request.body.read()) endpoint = body["endPoints"] resources = body["resources"] # check device's first occorrence if "id" in body: newDevice = Device(endpoint, resources, body["id"]) else: newDevice = Device(endpoint, resources) # read from config file jsonData = open(self.filePath).read() updateData = json.loads(jsonData) devices = updateData["devices"] if len(devices) > 0: for device in devices: if device["id"] == body["id"]: devices.remove(device) updateData["devices"].append(newDevice.getInfo()) # update data with open(self.filePath, "w") as outfile: json.dump(updateData, outfile) outfile.close() return Msg({ "action": "added new device", "device": newDevice.getInfo() }).info() elif uri[0] == "addUser": # read body body = json.loads(cherrypy.request.body.read()) name = body["name"] surname = body["surname"] email = body["email"] # create user newUser = User(name, surname, email) # read from config file jsonData = open(self.filePath).read() updateData = json.loads(jsonData) updateData["users"].append(newUser.getInfo()) # update data with open(self.filePath, "w") as outfile: json.dump(updateData, outfile) outfile.close() return Msg({ "action": "added new user", "id": newUser.getId() }).info() elif uri[0] == "addDivision": # read body divisionName = cherrypy.request.body.read() hc = HomeConfigurator(self.homeConfig) hc.newDivision(divisionName) return Msg("Added " + divisionName + " division").info() elif uri[0] == "addLight": body = json.loads(cherrypy.request.body.read()) divisionName = body["divisionName"] lightName = body["lightName"] hc = HomeConfigurator(self.homeConfig) hc.newLight(divisionName, lightName) return Msg("Added " + lightName + " light to " + divisionName + " division").info() elif uri[0] == "updateLightState": body = json.loads(cherrypy.request.body.read()) divisionName = body["divisionName"] lightName = body["lightName"] hc = HomeConfigurator(self.homeConfig) status = hc.updateLightState(divisionName, lightName) if status: return Msg("Updated " + lightName + " light state from " + divisionName + " division").info() else: return Msg("Could not update light state").error() elif uri[0] == "removeDivision": body = json.loads(cherrypy.request.body.read()) divisionName = body["divisionName"] hc = HomeConfigurator(self.homeConfig) status = hc.removeDivision(divisionName) if status: return Msg("Removed " + divisionName + " division").info() else: return Msg("Could not remove divisison").error() elif uri[0] == "removeLight": body = json.loads(cherrypy.request.body.read()) divisionName = body["divisionName"] lightName = body["lightName"] hc = HomeConfigurator(self.homeConfig) status = hc.removeLight(divisionName, lightName) if status: return Msg("Removed " + lightName + " light from " + divisionName + " division").info() else: return Msg("Could not remove light").error() else: return Msg("Invalid uri").error() else: return Msg("Invalid number of uris").error()
def msgHandler(pa, buf, action): buf += raw(pa) msg = Msg(buf) while msg: action(msg) msg = Msg(buf)
# -*- coding: utf-8 -*- from message import Msg msg = Msg() msg.drink() msg.weather() msg.send_markdown('喝口水吧', use_img=True)
# -*- coding: utf-8 -*- from message import Msg msg = Msg() msg.mao_tai() msg.send_msg()