Coding programming error using ActionScript - actionscript

I am wondering if anyone can help resolve my problem. I am using the NetConnection and NetStream classes to connect to a webcam feed using Flash Media Server. However, this appears every time in my output:
ArgumentError: Error #2126: NetConnection object must be connected. at flash.net::NetStream/ctor() at flash.net::NetStream()
I have tweaked around with the code but to no avail.
Any ideas as to why this isn't working? Here is the (I think relevant) code:
import flash.net.NetConnection;
import flash.events.NetStatusEvent;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
var nc:NetConnection = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
nc.connect("rtmfp://localhost//myUrlExample");
var ns:NetStream = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.publish("myStream", "recording");
function netHandler(event:NetStatusEvent):void{
switch(event.info.code){
case "NetConnection.Connect.Success":
trace("Successs");
break;
case "NetConnection.Connect.Failed":
trace("Cannot connect to the server");
break;
case "NetConnection.Connect.Rejected":
trace("Ouch!");
break;
}
}
function asyncErrorHandler(event:AsyncErrorEvent):void{
//ignore error;
}

It seems that you are creating and initializing both NetStream and NetConection before conductor call. Did you try putting that code inside constructor or any other function?

The problem is that you need to wait for the NetConnection to actually connect to the server before you try to publish() the NetStream.
You know when the connection has been established from the NetStatusEvent that you're already listening to. So inside the switch statement where the connection attempt succeeds, is when you should wire up the NetStream and publish it:
var nc:NetConnection = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
nc.connect("rtmfp://localhost//myUrlExample");
var ns:NetStream;
function netHandler(event:NetStatusEvent):void{
switch(event.info.code){
case "NetConnection.Connect.Success":
trace("Successs");
ns = new NetStream(nc);
ns.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
ns.publish("myStream", "recording");
break;
case "NetConnection.Connect.Failed":
trace("Cannot connect to the server");
break;
case "NetConnection.Connect.Rejected":
trace("Ouch!");
break;
}
}

Related

React native track player fails to add songs to playlist

I am working on a music player in react native and have been using the package react-native-track-player. I have so far not had a problem with the package in android. but when I try to run it on ios I get the error
You attempted to set the key0with the value
{"id":"0",
"url":{"uri":"https://urltosong.mp3"},
"artwork":"https://url_to_artwork.jpg",
"artist":"author",
"title":"song titile"
}
on an object that is meant to be immutable and has been frozen.
The code that generate the error is
async function togglePlayback() {
const currentTrack = await TrackPlayer.getCurrentTrack();
if (currentTrack == null) {
await TrackPlayer.reset();
await TrackPlayer.add(playlist); //this was never adding and die silently
await TrackPlayer.play();
} else {
await TrackPlayer.add(playlist); //adding this line the error above appeared
await TrackPlayer.play();
//console.warn(TrackPlayer.getCurrentTrack())
}
}
I am using this version of the package "react-native-track-player": "^2.0.0-rc13",
I don't know if there is something I am missing. I will appreciate your help in fixing this.
Change your track to this:
{"id":"0",
"url":"https://urltosong.mp3",
"artwork":"https://url_to_artwork.jpg",
"artist":"author",
"title":"song titile"
}
Urls should be either a string or a Resource Object

how to run a polymer app via "Run in Dartium" from console?

I want to call a polymer webapp directly via command line or via 'Process' in a dart file.
I know when running it via the dart editor, a server on port 8080 is created and listening to requests for the /web folder.
but when launching
dartium/chrome.exe path/To/Index.html
from console its simply loading the files inside the browser but wont start a server for the client.
via
file:://path/to/file.html [no 'dart is not runnning' warning, but no polymer content]
or
127.x.x.x.x.x.x.x.x:xxxxxxxx/app/index.html will obviously tell me
'This webpage is not available'
DartEditor lauches pub serve. You can do this manually without Darteditor (since Dart 1.5 AFAIK). Just launch
pub serve
from within your Polymer app package directory.
Inside your console app launch the browser with the URL that loads the page from this server.
You could also include web server functionality into your console application that serves the Polymer app to your browser.
pub help serve
lists the available options.
You can try this script as an example how to call a polymer webapp directly via 'Process' in a dart file.
This example also includes launch of default browser.
import "dart:async";
import "dart:io";
import "package:path/path.dart" as pathos;
void main(List<String> args) {
String app;
String file;
switch (args.length) {
case 1:
app = args[0];
break;
case 2:
app = args[0];
file = args[1];
break;
default:
print("Usage: pubserve.dart app_path [file_name]");
exit(0);
}
if(!new Directory(app).existsSync()) {
print("Directory not exists: $app");
exit(-1);
}
pubServe(app, file).then((exitCode) {
exit(exitCode);
});
}
Future<int> pubServe(String app, String file) {
var sdk = Platform.environment["DART_SDK"];
if (sdk == null) {
print("Dart SDK not found");
return new Future(() => -1);
}
var executable = pathos.join(sdk, "bin", "pub");
var pattern = r"^Serving (?:.*) web on (.*)$";
var regexp = new RegExp(pattern);
return Process.start(executable, ["serve"], runInShell: true,
workingDirectory: app).then((process) {
process.stdout.listen((data) {
var string = new String.fromCharCodes(data);
for (var c in data) {
stdout.writeCharCode(c);
}
var match = regexp.matchAsPrefix(string);
if (match != null) {
var url = match.group(1);
if (file != null) {
url += "/$file";
}
Timer.run(() => runBrowser(url));
}
});
process.stderr.pipe(stderr);
stdin.pipe(process.stdin);
return process.exitCode.then((exitCode) {
return exitCode;
});
});
}
void runBrowser(String url) {
var fail = false;
switch (Platform.operatingSystem) {
case "linux":
Process.run("x-www-browser", [url]);
break;
case "macos":
Process.run("open", [url]);
break;
case "windows":
Process.run("explorer", [url]);
break;
default:
fail = true;
break;
}
if (!fail) {
//print("Start browsing...");
}
}
P.S.
NOTE:
If you run this script from Dart Editor, Editor will never stops execution of subprocess (pub serve in our case) when you stop current script in Dart Editor.
This is not related only to this script. Editor always keep subprocesses alive.
If you run it from cmd-line it terminates pub serve correctly.

Close distant USSD session

I am working on a USSD client. Everything works fine except for closing a distant USSD session.
In the specification, we can see the function CUSD:
AT+CUSD=2 should close the USSD session, but this is not really the case.
In fact when I do this sequence:
AT+CUSD='#xxx#',12
AT+CUSD='1',12
I have an open distant connection.
On your handset, you can open a new session by dialing #xxx*#
If I send a:
AT+CUSD='#xxx*#',12
This is not opening a new distant session.
If I send a:
AT+CUSD=2
AT+CUSD='#xxx#'
This is not opening a new distant session.
Do you know how to close a distant session?
I am working with huwaei key E160 and E173 on windows or Linux.
Use in the following way.
AT+CUSD='#xxx#',15
AT+CUSD=2
I am posting this because this is the top result regarding terminating USSD sessions using AT commands and also because the answers are vague.
This is the c# code i used in the end(I was sending the commands to a gsm modem). Hope it helps someone else
SerialPort SendingPort=null;
public string TerminateUssdSession()
{
InitializePort();
//// generate terminate command for modem
string cmd = "";
cmd = "AT+CUSD=2\r";
// send cmd to modem
OpenPort();
SendingPort.Write(cmd);
Thread.Sleep(500);
string response = SendingPort.ReadExisting();
return response;
}
private void InitializePort()
{
if (SendingPort == null)
{
SendingPort = new SerialPort();
SendingPort.PortName = PortName;//put portname here e.g COM5
SendingPort.BaudRate = "112500";
SendingPort.Parity = Parity.None;
SendingPort.DataBits = 8;
SendingPort.StopBits = StopBits.One;
SendingPort.Handshake = Handshake.None;
SendingPort.ReadTimeout = 500;
}
}
private void OpenPort()
{
if (!SendingPort.IsOpen)
{
SendingPort.Open();
}
}

Reading / writing file on local machine

I pretty much copied this code right out of the MDN File I/O page.. except I added an if statement to check if the file exists already and if it does, read it instead.
Components.utils.import("resource://gre/modules/NetUtil.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("test.txt");
if (!file.exists()) {
this.user_id = Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001) +'-'+ Math.floor(Math.random()*10001);
var ostream = FileUtils.openSafeFileOutputStream(file)
var converter = Components.classes["#mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var istream = converter.convertToInputStream(this.user_id);
// The last argument (the callback) is optional.
NetUtil.asyncCopy(istream, ostream, function(status) {
if (!Components.isSuccessCode(status)) {
alert('Error '+ status);
return;
}
alert('File created');
});
} else
{
NetUtil.asyncFetch(file, function(inputStream, status) {
if (!Components.isSuccessCode(status)) {
alert('error '+ status);
return;
}
// The file data is contained within inputStream.
// You can read it into a string with
this.user_id = NetUtil.readInputStreamToString(inputStream, inputStream.available());
});
alert('File exists already, do not create');
}
alert(this.user_id);
It creates the file just fine, I can open it and read it. If the file already exists however, it does not populate this.user_id.. just equals null. So my issue is specifically with reading the file.
File reading in your code works asynchronously - meaning that your code completes (including the alert() call which will show that this.user_id is null), then at some point the callback from NetUtil.asyncFetch() gets called with the data. Until that happens this.user_id won't be set of course. If you move alert(this.user_id) into the callback function it should show the correct value.
Note that it is highly recommended to keep file I/O operations asynchronous because they might take significant time depending on the current state of the file system. But you have to structure your code in such a way that it doesn't assume that file operations happen immediately.

Querying Zebra printer status using RawPrinterHelper class

I'm using the RawPrinterHelper class from Microsoft, http://support.microsoft.com/kb/322091, to print to a Zebra KR403 printer from C# code, and everything is working fine.
I wish to monitor the status of the printer for paper jams and paper outages. I've found a query that I can send to the printer, "~HQES" or "esc eng 6", that will return everything I need. The problem is that I can not figure out how to send this query to the printer that will allow the printer to respond. The WritePrinter in the RawPrinterHelper class only seems to return a bool or long type.
I also tried using a Win32_printer object to find the PrinterStatus/PrinterState/Errors of the printer. using the following method:
public static string PrinterStateCheck(string szPrinterName)
{
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}%'", szPrinterName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
string errorName = "";
foreach (ManagementObject printer in collection)
{
int state = Convert.ToInt32(printer["PrinterState"]);
errorName = state.ToString();
}
return errorName;
Utilizing this method, I tried getting the PrinterState, PrinterStatus, and DetectedErrorState, but none of these respond with the information I need. PrinterState always returns a 1024, PrinterStatus always returns a 4, and DetectedErrorState always returns a 2. Though PrinterState did return a 0 on a proper printing and 1024 on a paperjam or media out event for a few prints, now it just returns 1024 on every call.
I have also found that Zebra created their own software for monitoring printers on a network. The problem is our printers are not on a network and are only connected to the client computer via USB. Also, we are hoping to check the status of the printer prior to or after each receipt is printed.
I am hoping there is something from the winspool.Drv that I can use to send raw data to the printer and receive data back from the printer.
Now I'm using the ReadPrinter function of the winspool.Drv, but the function is returning 0 which means that a response from the printer cannot be accessed. This usually means that the printer is not setup for bidirectional communication, but I'm sure that it is. The "Enable bidirectional support" check box is checked in the "Ports" tab of the Printer Properties. Also, the Zebra Setup Utilities can correctly query the printer and receive a response in its Direct Communication window.
Thanks for any advice,
Jeremy
I've done something very similar and i can tell you that there is almost no way at all to monitor print jobs in .NET.
I've gotten close though, doing the following:
Create a "PrinterDiagnosticsFacade" that queries both the .NET PrintQueue object's status and WMI. Neither are always accurate. Merge the data from both to decide the printer's true status.
Adjust the printer's settings so that print jobs stay in the queue. That way you can accurately read the print job's status by doing a WMI query for the print spool jobs. (You can match against the print filename)
Thats how i got close to getting at printer status.
Adding in code to show how its done using the .NET print queue object:
See http://msdn.microsoft.com/en-us/library/system.printing.printqueue.aspx for the printqueue object that starts the code off
PrintQueue me = Queue;
if (me != null)
{
me.Refresh();
//in this if else,
//i purposefully put the ones that error out first
//so that if multiple can be true at the same time
//the errors will definitely take precedence
if (me.HasPaperProblem)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Has paper problem");
}
else if (me.IsDoorOpened)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Door is open");
}
else if (me.IsManualFeedRequired)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Printer needs manually fed");
}
else if (me.IsNotAvailable)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Printer not available");
}
else if (me.IsOutOfMemory)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Printer is out of memory");
}
else if (me.IsOutOfPaper)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Printer is out of paper");
}
else if (me.IsOutputBinFull)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Printer output bin is full");
}
else if (me.IsPaperJammed)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Error, "Error: Paper jam");
}
else if (me.IsOffline)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Offline, "Offline");
}
else if (me.IsBusy)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Busy");
}
else if (me.IsInitializing)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Initializing");
}
else if (me.IsIOActive)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Sending and recieving data");
}
else if (me.IsProcessing)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Processing");
}
else if (me.IsWarmingUp)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Warming up");
}
else if (me.IsPendingDeletion)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Busy, "Deleting a job");
}
else if (me.IsPaused)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Paused, "Paused");
}
else if (me.IsPrinting)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Printing, "Printing");
}
else if (me.IsPowerSaveOn)
{
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Ready, "In power save mode");
}
else
_SystemDotPrintingStatus = new PrinterStatus(PrinterStatusType.Ready, "Ready");
}
The solution to the problem that we ended up utilizing was to create a WinUSB driver for the printer. This way the device is treated as a USB device. A ZebraUSB object was created using the driver and a method called WriteRead was created. Using the WriteRead method we sent the ~HQES query to the printer and received a response. Sometimes there is some lag time between the query and the response. To combat this, we set the response to a variable and retrieve it using a different method.
I'm not sure of the specifics of the code because I did not code the WinUSB driver, and I do not have access to its code.
The main point of this answer is that we had to create a WinUSB driver for the printer before any of the status queries could work.

Resources