def _on_response(self, response: Response) -> None: # called from tornado thread message = json_encode(response) try: self.write_message(message) except WebSocketError: # The websocket is dead. If the response was a Delta or Update, then # unsubscribe so the local controller doesn't keep on trying to # respond if isinstance(response, (Delta, Update)): # Websocket is dead so we can clear the subscription key. # Subsequent updates may come in before the unsubscribe, but # ignore them as we can't do anything about it mri = self._id_to_mri.pop(response.id, None) if mri: log.info("WebSocket Error: unsubscribing from stale handle") unsubscribe = Unsubscribe(response.id) unsubscribe.set_callback(self.on_response) if self._registrar: self._registrar.report( builtin.infos.RequestInfo(unsubscribe, mri) ) finally: assert self._queue, "No queue" cothread.Callback(self._queue.put, None)
def post(self, mri, method, args): req = HTTPRequest( "http://localhost:%s/rest/%s/%s" % (self.socket, mri, method), method="POST", body=args, ) result = yield self.http_client.fetch(req) cothread.Callback(self.result.put, result)
def post(self, mri, method, args): req = HTTPRequest( f"http://localhost:{self.socket}/rest/{mri}/{method}", method="POST", body=args, ) result = yield self.http_client.fetch(req) cothread.Callback(self.result.put, result)
def Thread(): for pv in sys.argv[1:]: print(pv, '=>', end=' ') try: v = cothread.CallbackResult(caget, pv) print(v) except: print('failed') traceback.print_exc() cothread.Callback(cothread.Quit)
def unsubscribe_all(self, callback=False): """Send an unsubscribe for all active subscriptions""" futures = ((f, r) for f, r in self._requests.items() if isinstance(r, Subscribe) and f not in self._pending_unsubscribes) if futures: for future, request in futures: if callback: log.warning(f"Unsubscribing from {request.path}") cothread.Callback(self.unsubscribe, future) else: self.unsubscribe(future)
def send_messages(self, messages, convert_json=True): conn = yield websocket_connect("ws://localhost:%s/ws" % self.socket) num = len(messages) for msg in messages: if convert_json: msg = json_encode(msg) conn.write_message(msg) for _ in range(num): resp = yield conn.read_message() resp = json.loads(resp) cothread.Callback(self.result.put, resp) conn.close()
def sendWfToPv(self, pv_name): try: #print("[debug] self.msg: %s" % self.msg); #print("[debug] len(self.msg): %s" % len(self.msg)); if len(self.msg) != 0: cothread.Callback(caput, pv_name, self.msg) return True return False except Exception as e: print("Trouble when Publishing to PV with " + pv_name + ": " + str(e)) logging.info("Trouble when Publishing to PV with " + pv_name + ": " + str(e))
def producer(event, count): ''' this is a different thread from that running the cosumer code''' for n in "ABCDE": print('thread tick', n) try: # can't Signal from a different thread if n == "E": event.Signal(n) except AssertionError as e: print(f"{e}") # must use the following to talk across thread boundaries: cothread.Callback(signalViaCallback, n) time.sleep(0.5)
def updatePv(self, value): try: pv_val = value if self.datatype == "wfint": self.wfToWf(value) else: if self.datatype == "wfint1": pv_val = self.wfToScalar(value) elif self.datatype == "int": pv_val = self.intToScalar(value) cothread.Callback(caput, self.pv, pv_val) except Exception as e: print("Trouble in updatePv with " + self.pv + ":\n" + traceback.format_exc()) logging.info("Trouble when Publishing to PV with " + self.pv + ": " + str(e))
def get(self, mri): result = yield self.http_client.fetch("http://localhost:%s/rest/%s" % (self.socket, mri)) cothread.Callback(self.result.put, result)
def spawn(self, f, *args, **kwargs): """Can be called from any thread""" cothread.Callback(self.q.Signal, (f, args, kwargs))
def signaller(name): n = 0 while True: n += 1 cothread.Callback(do_signal, name, n) time.sleep(0.1 * numpy.random.random())
def get(self, mri): result = yield self.http_client.fetch( f"http://localhost:{self.socket}/rest/{mri}") cothread.Callback(self.result.put, result)
def _communicate_thread(self, input_): """Executes in separate OS thread. Wait for communication then return the output to the cothread context. """ output = self._process.communicate(input_) cothread.Callback(self._communicate_callback, output)