def getChild(self, name, request): ev = { 'event': 'setlesson', 'lesson': name, } messages.send(ev, 50000) return StringResource("")
def send(): content = request.form["content"] if len(content) < 1 or len(content) > 200: render_template("error.html", message="Viestin pitää olla 1-200 merkkiä pitkä") chain_id = request.form["chain_id"] messages.send(content, chain_id) return redirect("/chain/"+chain_id)
def associate(self,args): print "In associate" print "after bp" try: if not (args["devid"] in self.rostermap) and not (self.finished) and self.started: currentstudent = self.rosterlist[self.rosterpos] self.rostermap [args["devid"]] = currentstudent ev = { 'event': 'studentmapping', 'devid': args["devid"], 'student': currentstudent, } messages.send(ev, 50000) self.rosterpos +=1 if self.rosterpos >= len(self.rosterlist): self.finished = True self.rosterpos = len(self.rosterlist) print "Finished registration" else: print "%s already in rostermap" % args["devid"] except Exception, e: print self.rosterpos print "Malformed button event" print e
def release(self): if not (self.isInit()) or self.isActive(): return logging.info("LASER_CLASS release") msg.send('prime', "Laser Emulator released") self._init = False self.x = False self.y = False self.mode = ""
def render_GET(self, request): print "In Button" ev = { 'event': 'rawbuttonpress', 'rawtime': 'now', 'devid': self.devid, 'button': self.buttonname, } messages.send(ev, 50000) return ''
def pyserver_core_publish_message(): """ Allows for publishing of a local message. """ if request.json: msg = json.dumps(request.json) else: data = request.values.to_dict(flat=False) msg = convert_types_in_dictionary(remove_single_element_lists(data)) msg = json.dumps(msg) messages.send(msg, messages.LOCAL_PUBLISH) return dict(message="ok")
def receive_from_master_callback(ch, method, properties, body): ch.basic_ack(delivery_tag=method.delivery_tag) received_data = ts.decode_obj(body) print(" [x] Slave received task from master") message = ts.json_to_str(cm.crop_map(received_data)) #SEND: slave TO master msg.send(m_s_channel, s_to_m_queue, message) print(" [x] Slave sent map to master")
def receive_from_master_callback(ch, method, properties, body): ch.basic_ack(delivery_tag=method.delivery_tag) print(" [x] Frontend received maps from master") message = body.decode() #SEND: frontend TO cliend msg.send(c_f_channel, f_to_c_queue, message) print(" [x] Frontend sent maps to client") ch.stop_consuming()
def presetupbuttonpress(self,args): if args["button"] in getbuttonlist(): messages.send(args, 50001) elif args["button"] == "startregistration": print "Start registration" self.startregistration() elif args["button"] == "restart": ev = {'event': 'restart'} messages.send(ev, 50001) self.restart() elif args["button"] == "startlesson": self.startlesson()
def _stop_handler(self, data): try: rospy.loginfo('Received: ' + data) msg = messages.parse(data) except Exception as e: rospy.logwarn('Could not parse data: %s (%s)' % (str(data), e)) else: response = [comm.params['id']] response_msg = messages.create('stop-resp', comm.params['id'], msg['orig'], 'comm_receiver', response) messages.send(comm.params['ports'][msg['orig']], response_msg) rospy.loginfo('Sent: ' + response_msg)
def receive_from_client_callback(ch, method, properties, body): ch.basic_ack(delivery_tag=method.delivery_tag) print(" [x] Frontend received body from client") received_data = body message = received_data #SEND: frontend TO master msg.send(f_m_channel, f_to_m_queue, message) print(" [x] Frontend sent envelope to master") #RECEIVE: frontend FROM master msg.receive(f_m_channel, m_to_f_queue, receive_from_master_callback)
def main(self): neighbors = self._search_neighbor() #TODO: BT-find neighbors #get the near node the robot is approaching self.current_node, distance = comm.get_current_node() if not self.current_node and distance == 0.0: #rospy.loginfo('No current node and just pass this iteration') return if self.current_node != self.last_node: rospy.loginfo('Switch from node %s to %s'%(self.last_node['id'], self.current_node['id'])) if comm.state == 'IDLE': if distance < comm.params['threshold'] and self.current_node == self.last_node: for dest in neighbors: msg_content = [comm.params['id']] msg = messages.create('request',comm.params['id'], dest,'comm_checker', msg_content) messages.send(comm.params['ports'][dest],msg) rospy.loginfo('Sent: '+ msg) comm.state = 'QUERY' rospy.loginfo('Current State: %s'%comm.state) elif comm.state == 'DONE': if distance < comm.params['threshold'] and self.current_node == self.last_node: for dest in neighbors: msg_content = [comm.params['id']] msg = messages.create('request',comm.params['id'], dest,'comm_checker', msg_content) messages.send(comm.params['ports'][dest],msg) rospy.loginfo('Sent: '+ msg) comm.state = 'QUERY' rospy.loginfo('Current State: %s'%comm.state) if self.current_node != self.last_node: for dest in neighbors: msg_content = [comm.params['id']] msg = messages.create('stop',comm.params['id'], dest,'comm_checker', msg_content) messages.send(comm.params['ports'][dest],msg) rospy.loginfo('Sent: '+ msg) comm.approaching_dict.clear() comm.state = 'IDLE' rospy.loginfo('Current State: %s'%comm.state) elif comm.state == 'QUERY': if self.current_node != self.last_node: for dest in neighbors: msg_content = [comm.params['id']] msg = messages.create('stop',comm.params['id'], dest,'comm_checker', msg_content) messages.send(comm.params['ports'][dest],msg) rospy.loginfo('Sent: '+ msg) comm.approaching_dict.clear() comm.state = 'IDLE' rospy.loginfo('Current State: %s'%comm.state) self.last_node = self.current_node self.rate.sleep()
def sendMessage(self, uri, recipients, date, disappearing=False): recipients = self.__class__.getAllRecipients(recipients) for user in recipients: if isinstance(user, str): if not user in self.pendingcontacts: self.pendingcontacts.append(user) elif not user.key in self.contacts: self.contacts.append(user.key) self.put() messages.send(uri, self, recipients, date, disappearing=disappearing) return self.getContactList()
def send(): content = request.form["content"] if messages.send(content): return redirect("/") else: return render_template("error.html", message="Viestin lähetys ei onnistunut")
def _request_handler(self, data): try: rospy.loginfo('Received: ' + data) msg = messages.parse(data) except Exception as e: rospy.logwarn('Could not parse data: %s (%s)' % (str(data), e)) else: response = [ comm.params['id'], comm.current_node['id'], comm.current_distance, comm.current_vel ] response_msg = messages.create('request-info', comm.params['id'], msg['orig'], 'comm_receiver', response) messages.send(comm.params['ports'][msg['orig']], response_msg) rospy.loginfo("Sent: " + response_msg)
def processbuttonnet(self,args): if (args["devid"] in self.idtostudentmap): student = self.idtostudentmap[args["devid"]] print student ev = { 'event': 'processedbuttonpress', 'student': student, 'button': args['button'], 'realtime': args['rawtime'] } else: ev = { 'event': 'anonbuttonpress', 'button': args['button'], 'realtime': args['rawtime'] } messages.send(ev, 50001)
def send(): if session["csrf_token"] != request.form["csrf_token"]: abort(403) content = request.form["content"] if messages.send(content): return redirect("/forumIndex") else: return render_template("error.html", message="Viestin lähetys ei onnistunut")
def main(): filename = sys.argv[1] parts_num = int(sys.argv[2]) gjson_str = load_json_str(filename) c_f_connection, c_f_channel, c_to_f_queue, f_to_c_queue = msg.init_client_and_frontend_communication( ) message = ts.encode_obj(ts.Envelope(gjson_str, parts_num)) #SEND: client TO frontend msg.send(c_f_channel, c_to_f_queue, message) print(" [x] Client sent envelope to frontend") #RECEIVE: client FROM frontend msg.receive(c_f_channel, f_to_c_queue, receive_callback) print(" [x] Client received maps from frontend") c_f_connection.close()
def release(self): if not (self.isInit()): return try: self.stop() time.sleep(0.5) self.unlock() time.sleep(0.2) finally: try: self.nano.reset_usb() time.sleep(0.2) finally: try: self.nano.release_usb() finally: self.nano.dev = None self.mode = "" self.active = False logging.info("LASER_CLASS released") msg.send('prime', "K40 Laser released")
def send(): name = request.form["name"] place = request.form["place"] vacc = request.form["vacc"] date = request.form["date"] vaccname = request.form["vaccname"] if messages.send(name, place, vacc, date, vaccname): return redirect("/") else: return render_template("error.html", message="Viestin lähetys ei onnistunut")
def send(): content = request.form["content"] error_messages = [] append_string_length_error(error_messages, content, "message", 1, 1000) if len(error_messages) > 0: return render_template("error.html", messages=error_messages) if messages.send(content): return redirect("/") else: return render_template("error.html", message="Failed to send the message.")
def init(self, unit="mm", verbose=False): # set unit if unit == "in" or unit == "inch": self.unit = "in" self.scale = 1000 else: self.unit = "mm" self.scale = 1000 / 25.4 # connect and init laser main board self._stop_flag[0] = False self.release() idle() self.nano.initialize_device(verbose) idle() if self.nano.say_hello() != self.OK: self.release() return time.sleep(1) self.home() msg.send('success', "K40 Laser connected")
def receive_from_frontend_callback(ch, method, properties, body): ch.basic_ack(delivery_tag=method.delivery_tag) received_data = ts.decode_obj(body) print(" [x] Master received envelope from frontend") #get number of consumers availible queue_state = m_s_channel.queue_declare(queue=m_to_s_queue, durable=True) workers_num = int(queue_state.method.consumer_count) gjson = ts.str_to_json(received_data.map_str) task_arr = ts.get_tasks(received_data.parts_num, gjson) #calculate master's portion master_portion = len(task_arr) // (workers_num + 1) for i in range(master_portion, len(task_arr)): #SEND: master TO slave msg.send(m_s_channel, m_to_s_queue, ts.encode_obj(task_arr[i])) print(" [x] Master sent task to slave") #master does it's work splitted_maps.clear() for i in range(0, master_portion): splitted_maps.append(ts.json_to_str(cm.crop_map(task_arr[i]))) print(" [x] Master processed it's part of work") for i in range(master_portion, len(task_arr)): #RECEIVE: master FROM slave msg.receive(m_s_channel, s_to_m_queue, receive_from_slave_callback) print(" [x] Master received map from slave") #SEND: master TO frontend message = ts.str_list_to_one_str(splitted_maps) msg.send(f_m_channel, m_to_f_queue, message) print(" [x] Master sent maps to frontend")
def new(): if request.method == "GET": return render_template("new.html") if request.method == "POST": topic = request.form["topic"] content = request.form["content"] if len(topic) > 100: return render_template("error.html", cause="Your title has too many characters.") if len(content) > 5000: return render_template("error.html", cause="Your message has too many characters.") if messages.send(topic, content): return redirect("/") else: return render_template("error.html", cause="Message was not. Please, try again.")
def sendmessage(topic_id): if users.token() != request.form["csrf_token"]: abort(403) content = request.form["content"] user_id = users.user_id() if user_id == 0: return redirect("/topic/" + str(topic_id) + "/newmessage") sql_report = messages.send(content, topic_id, user_id) if sql_report[0]: return redirect('/topic/' + str(topic_id)) return render_template("newmessage.html", t_id=topic_id, message=sql_report[1], additional=sql_report[2])
def run(self, id = None): profile = self._activeProfile if self.laser.isActive() or not(profile): return if id is None: # process all tasks tasks = profile.tasks else: # find task by id for task in profile.tasks: if task.id == id: tasks = [task] break else: # id not found return for task in profile.tasks: task.status = "wait" if task in tasks else "---" task.progress = 0.0 self.laser.enable() for task in tasks: self._activeTask = task if task.type == Task.VECTOR: self.runVectorTask(task) else: self.runRasterTask(task) # get final status of task idle() task.status = self.laser.mode task.progress = self.laser.progress if task.status == "error" or task.status == "stopped": break self.laser.home() msg.send('success', profile.name + " finished")
def associate(self, args): print "In associate" print "after bp" try: if not (args["devid"] in self.rostermap) and not (self.finished) and self.started: currentstudent = self.rosterlist[self.rosterpos] self.rostermap[args["devid"]] = currentstudent ev = {"event": "studentmapping", "devid": args["devid"], "student": currentstudent} messages.send(ev, 50000) self.rosterpos += 1 if self.rosterpos >= len(self.rosterlist): self.finished = True self.rosterpos = len(self.rosterlist) print "Finished registration" else: print "%s already in rostermap" % args["devid"] except Exception, e: print self.rosterpos print "Malformed button event" print e
def new_message(to_id): user_id = users.user_id() if user_id == 0: flash(f'Kirjaudu jotta voit voit lähettää viestin', 'danger') return redirect("/") form = new_mesageForm() if form.validate_on_submit(): content = form.message.data if messages.send(content, to_id): flash(f'Viesti lähetetty {form.message.data}!', 'success') return redirect("/") else: flash('Voi hitsi! Viestin lähettäminen ei onnistunut', 'danger') return render_template('message.html', title='Lähetä viesti', form=form)
def handler(event, context): data = json.loads(event["body"]) json.dumps(data, indent=4, ensure_ascii=False) from_id = data['message']['from']['id'] message = data.get('message') if message.get('text'): message_text = message.get('text') if message_text == '/start': user.upload(from_id, os.getenv('INFO_FILENAME'), '') user.upload(from_id, os.getenv('TASK_FILENAME'), '') user.update_info(data) return send(from_id, text.get('welcome'), 'null') else: try: last_message = user.get_info(data)['last_message'] except KeyError: last_message = None finally: user.update_info(data) if message_text == 'Добавить задачу': return send(from_id, text.get('task_add'), last_message) elif message_text == 'Посмотреть список': task_list = task.all(data) if task_list is None: return send( from_id, text.get("task_list_empty"), last_message, ) else: return send( from_id, "{} \n{}".format(text.get('task_list'), task_list), last_message) elif message_text == 'Удалить': return send(from_id, text.get('task_delete'), last_message) else: task.add(data) return send(from_id, text.get('task_added'), last_message) else: return send(from_id, text.get('not_response'))
def processVector(self, polylines, feedRate, originX=0, originY=0, repeat=1): if not (self.isInit()) or self.active: return self.active = True filename = datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S.gcode") try: logging.info("LASER_CLASS processVector") self.progress = 0 self.mode = "prepare" path = "HTML/emulator" mkpath(path) path = os.path.join(path, filename) # save G-code file = open(path, "w") with open(path, 'a') as file: file.write( "; use https://ncviewer.com/ or http://gcode.ws/ to analyze G-code\n" ) file.write("\n") file.write("; Origin: ({:.2f}, {:.2f})\n".format( originX, originY)) file.write("; number of lines: {}\n".format(len(polylines))) file.write("\n") file.write("M452\t; set laser mode units to mm\n") file.write("G21\t; set units to mm\n") file.write("G90\t; absolute positioning\n") file.write("G28\t; home\n") file.write("G0 Z1 E0\t; WORKAROUND for G-Code Viewer\n") file.write("M83\t; E1 WORKAROUND for G-Code Viewer\n") for i, line in enumerate(polylines): p = line.getPoints() file.write("; polyline #{}\n".format(i)) if len(p) > 1: if not self.active: raise RuntimeError("stopped") idle() file.write("G0 X{:.2f} Y{:.2f}\n".format( p[0][0], p[0][1])) for x in p: file.write("G1 X{:.2f} Y{:.2f} E1\n".format( x[0], x[1])) idle() logging.info("EMULATOR save to: " + filename) msg.send('prime', "EMULATOR save to: " + filename) # # simulate cutting time # logging.debug("simulate cutting time ...") # self.mode = "running" # for i in range(0,10): # self.progress = i*10 # time.sleep(1) # if not self.active: # raise RuntimeError("stopped") # idle() self.progress = 100 self.mode = "finished" logging.info("LASER_CLASS processVector finished") except Exception as e: if self.active: self.mode = "stopped" else: self.mode = "error" logging.error("LASER_CLASS processVector ERROR: " + str(e)) finally: self.active = False self.jobList.append({ 'name': filename, 'status': self.mode, 'timestamp': int(time.time() * 1000) })
def send_msg(self,msg): messages.send(msg,50000)
def createfoundhandset(devid): return lambda req: messages.send( { "event": "foundhandset", "devid": devid, },50000)
def createfounddisplay(devid): return lambda req: messages.send( { "event": "founddisplay", "devid": devid, },50000)
def emit_local_message(source, message=None): if source in app.config['LOCAL_EVENT_SOURCES']: wrapped = json.dumps(dict(source=source, message=message, user_token=g.user_token)) messages.send(wrapped, messages.LOCAL_PUBLISH)
def senddisplaymsg(self, text): for d in self.displays: messages.send({"event":"display", "text": text, "devid":d}, 50001)
def startregistration(self): self.registrationstarted = True ev = { 'event': 'startregistration' } messages.send(ev, 50001) for h in self.handsets: messages.setlight(h, "#ffffff")
def send_msg(self, msg): messages.send(msg, 50000)