Oldschool question: Wardialers, what condition tested to see if another computer was connected? - modem

I was wondering what conditions were used to check the connection at the other end of the line.
Case 1: Computer dials a number, and a human picks up the phone, computer disconnects and moves on to the next phone number.
Case 2: Computer dials a number, and a modem answers, computer disconnects and records the number as being a computer.
What sort of if/else statement would be used for this?

You could of course do it recursively, using something similar to this...
void TryNumber(int _number)
{
if(_number > m_maxNumber) return; // exit out from the method if we've gone over our max number to dial
DialNumber(_number);
if(m_modemToneDetected) m_modemList.Add(number); // add number to a list if it's a modem
TryNumber(_number + 1); // and back in to the method again!
}
m_modemToneDetected being a boolean that would be adjusted during the call to DialNumber()

while(currentNumber < numbersToDial)
{
DialNumber(number)
if(ModemToneDetected)
{
// it's a computer
AddNumberToList(number);
}
else
{
// it's not a computer
}
}

Related

Communication between objects

If I have Game Class, which has Player object and Board object, Game asks Player what are the coordinates, Player responds, then game checks Board for the coordinates and the result either Hit or Miss.
How can Game forward the result back to Player? so that Player uses the result to set the new coordinates.
I have created code sample below to explain more what i want to do
and also a link to the project here: https://github.com/hythm7/Battleship/tree/master
#!/usr/bin/env perl6
enum Result < Miss Hit >;
class Player {
method fire ( ) {
(^10).pick, (^10).pick
}
}
class Board {
has #.cell = [ +Bool.pick xx ^10 ] xx ^10;
}
class Game {
has Board $.board = Board.new;
has Player $!player = Player.new;
method run ( ) {
loop {
my ($x, $y) = $!player.fire;
if $!board.cell[$y][$x] {
say Hit;
}
else {
say Miss;
}
# How to forward the above result (Hit or Miss) back to the Player object? so
# it can set $y, $x accordingly for the next call to $player.fire
sleep 1;
}
}
}
my $game = Game.new;
$game.run;
Let's see. The main question here is a design one, I think, so let's go for it from this angle. I want to note beforehand that I will describe just a single example of the approach: there are a lot of ways to do it, and I am writing out the simplest I can imagine that works. Also, for the sake of simplicity, code that deals with synchronization, graceful termination and so on is omitted.
Firstly, you have a player to be a separate thing, but in your code it reacts only when it is called from the outside. When it looks like a natural approach when implementing turn-based games, we still want to have some kind of communication. What if a player leaves? What if there is some error condition?
And as you noted the server wants to notify the player about outcome of the game. It seems like we want to have a bi-directional messaging between our Server and Player. Of course, if there is a One Server -> Many Players relation, it is another deal, but we will keep it simple.
Let's prepare some boilerplate code:
# We will get to this `Start` later
enum EventType <Start Hit Miss>;
# A handy class to hold a position, and likely some other data in the future
class Position {
has Int $.x;
has Int $.y;
}
# A board
class Board {
has #.cell = [ +Bool.pick xx ^10 ] xx ^10;
}
Now here is a server:
class Server {
has Board $!board = Board.new;
has Supply $.shots;
has Channel $.player;
method serve {
react {
# Whenever we get a shot coordinates, sent a Hit or Miss to the player
whenever $!shots -> Position $pos {
$!player.send($!board.cell[$pos.y][$pos.x] ?? Hit !! Miss);
# Don't forget to say "I am ready for new events" for the client
$!player.send(Start);
}
# Somebody should start first, and it will be a Server...
$!player.send(Start);
}
}
}
It has a board, and two other attributes - a Supply $.shots and a Channel $.player. If we want to tell something to our player, we are sending a message to the channel. At the same time, we want to know what player wants us to know, so we are listening on everything that comes from our $!shots async stream of values.
The serve method just does our logic - reacts to player's events.
Now to our Player:
class Player {
has Channel $.server;
has Supply $.events;
method play {
react {
whenever $!events {
when Start {
# Here can be user's input
# Simulate answer picking
sleep 1;
$!server.send: Position.new(x => (^10).pick, y => (^10).pick);
# Can be something like:
# my ($x, $y) = get.Int, get.Int;
# $!server.send: Position.new(:$x, :$y);
}
when Hit {
say "I hit that! +1 gold coin!";
}
when Miss {
say "No, that's a miss... -1 bullet!"
}
}
}
}
}
Player has a Channel and a Supply too, as we want a bi-directional relationship. $!server is used to send actions to the server and $!events provides us a stream of events back.
The play method is implemented this way: if the server says that it is ok with our action, we can made our move, if not - we are basically waiting, and when a Hit or Miss event appears, we react to it.
Now we want to tie those two together:
class Game {
has Server $!server;
has Player $!player;
method start {
my $server-to-player = Channel.new;
my $player-to-server = Channel.new;
$!server = Server.new(player => $server-to-player,
shots => $player-to-server.Supply);
$!player = Player.new(server => $player-to-server,
events => $server-to-player.Supply);
start $!server.serve;
sleep 1;
$!player.play;
}
}.new.start;
Firstly, we are creating two channels with self-contained names. Then we create both Server and Player with those channels reversed: player can send to the first one and listen to the second one, server can send to the second one and listen to the first one.
As react is a blocking construct, we cannot run both methods in the same thread, so we start a server in another thread. Then we sleep 1 second to make sure it serves us(that's a hack to avoid negotiation code in this already pretty long answer), and start the player (be it emulation or a real input, you can try both).
Modifying the handlers and the data types sent between Player and Server you can build more complex examples yourself.
One way to do it is to add a Board to the player. If you make it $.board then you get at least a public read accessor which you'll be able to use in the Game class and if you make it is rw you'll get a write accessor so you can just write it.
So, add the Board to Player:
class Player {
has Board $.board is rw = Board.new;
method fire ( ) {
(^10).pick, (^10).pick
}
(And for that to compile you'll need to move the Board class declaration above Player otherwise you'll get a Type 'Board' is not declared error.)
And now you can add a line like this somewhere in the Board class:
$!player.board.cell[$y][$x] = Hit; # or Miss
Also, you need to record one of three states in the cells of the player's board, not two -- Hit, Miss, or unknown. Maybe add Unknown to the enum and initialize the player's board with Unknowns.

Issue with syncing data between watch and phone

I have developed an Android App which runs on both a smartphone and a smartwatch in parallel. On both devices, (let's say) it reads certain sensor data, processes that data (calculate its mean), and then store that results. The watch sends this result to the phone so all storing takes place on the phone. I used buffer writer to write a number into a text file every 5 seconds.
Now after every 320 data items exchanges from watch to the phone, my app on the phone gets killed and I get "the name of the app" is unfortunately stopped as a message. I can't figure it what why they stop exactly after this time? The app running on the watch continues to work fine. However, I cannot store its data because it cannot communicate to the phone version so I get this message "the app is unfortunately stopped as a message" every time the watch sends a number to phone for storing. The app has one activity which has a service (foreground).
Could it be that there is a limit on the amount of data being shared?
The code on watch:
// Create a data map and put data in it
private void increaseCounter() {
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/count");
putDataMapReq.getDataMap().putInt(COUNT_KEY, count++); // I add current time here as well
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult =
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
}
Code on phone (possible problematic area):
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo("/count") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
updateCount(dataMap.getInt(COUNT_KEY));
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
}
You have to use Service with StartForeground notification to be sure app is always working.
and try to use START_STICKY flag while staring.
UPDATE
You have to dealloc memory of dataevent:
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
try{
for(DataEvent dataEvent: dataEvents){
if(dataEvent.getType() != DataEvent.TYPE_CHANGED){
continue;
}
////... code
dataEvents.release();
}catch (Exception e){
Log.v("SunshineWatchFace",e.getMessage());
}
}

C++ pipe process not terminating

I made a program that takes two commands typed in by the user and pipes the first into the second. It works fine if real commands are entered but I'm having a problem getting my error check to work when I just enter random words. In most places of my code where I use exit() the process terminates fine but within the two child processes rs1 and rs2, I cannot exit. I'm new to processes so I'm not sure how to do this correctly. Can someone help?
int main()
{
while(true)
{
int argc1=0,argc2=0,rs1,rs2,pipefd[2];
char input1[80],input2[80],*argv1[6],*argv2[6],*p1,*p2;
//*Big block of code that receives input goes here*
pipe(pipefd);
rs1=fork();
rs2=fork();
if(rs1==0)
{
close(pipefd[0]);
close(1);
dup(pipefd[1]);
close(pipefd[1]);
rs1=execvp(argv1[0],argv1);
if(rs1==-1)
{
perror(argv1[0]);
exit(rs1); //Here is where I'm having the problem
}
}
if(rs2==0)
{
close(pipefd[1]);
close(0);
dup(pipefd[0]);
close(pipefd[0]);
rs2=execvp(argv2[0],argv2);
if(rs2==-1)
{
perror(argv2[0]);
exit(rs2); //Here also does not work correctly
}
}
close(pipefd[0]);
close(pipefd[1]);
wait(&rs1);
wait(&rs2);
}
return 0;
}

Arduino: UDP sending yields extra characters

At the moment I have an Arduino board with an Ethernet Shield connected to a router. My computer connects to this router via Wi-Fi. My board and my computer send UDP messages back and forth to each other. My computer is a client, and the board is a server. However I noticed, that when I send a longer UDP message from my computer, and then a shorter UDP message, the Arduino accepts the shorter message, then followed by remaining bits from the longer message.
For instance: if I send "Hello World" from my computer, followed with "Test"; the Arduino will not read the second message as "Test", but rather: "Testo World".
I thought perhaps in was a problem from the Arduino end first. The Arduino stores the messages temporarily in an array called packetBuffer. I tried clearing this buffer before I receive a new message each time. The buffer would clear, but then I would receive the faulty message again.
So I assume the culprit is the computer, the client. On the computer end I have a processing sketch that sends the UDP messages. The example below is not the sketch itself; however it is by far a simpler example that still provides the exact symptoms as I described with my original sketch.
import hypermedia.net.*;
UDP udp; // define the UDP object
void setup() {
udp = new UDP( this, 6000 ); // Create a new datagram connection on port 6000
//udp.log( true ); // <-- printout the connection activity
udp.listen( true ); // and wait for incoming message
}
void keyPressed() {
String IPaddress = "192.168.1.177"; // The remote IP address
int port = 8888; // The destination port
if (keyCode == UP)
{
udp.send("Test", IPaddress, port );
}
else
if (keyCode == DOWN)
{
udp.send("Hello World", IPaddress, port );
}
}
void receive( byte[] data ) { // <-- default handler
//void receive( byte[] data, String IPaddress, int port ) { // <-- extended handler
for(int i=0; i < data.length; i++)
print(char(data[i]));
println();
}
How could I get the sketch to send the right messages?
Of course I am more than willing to provide more information.
There wasn't a direct solution to this problem; so I ended up resorting to a work around. The work around involves dynamically adding zeros to all strings sent to the Arduino so there is always 10 characters sent.
For instance:
If I am to send "Hello Bot", the actual string sent is "Hello Bot0". If I sent an additional message like "Test" after that, the string sent to the Arduino would be "Test000000". The additional zeros would cover up the overlapping characters. One problem with this work around is that I had to prepare the Arduino to accept the zeros also. This work around is also kind of messy for the code. It does work though.
Here's a snippet of code from the computer (client) side. The Arduino code obviously just had to be adjusted to account for the zeros.
public void Send() { //bang button named "Send" activates function
String txtSend = comField.getText(); //Grab text from a textbox to be sent
int txtSendLength = txtSend.length();
for(int i = 0; i < 10-txtSendLength; i++){ //Add zeros until it has 10 char
txtSend = txtSend + "0";
}
udp.send(txtSend, ip, port);
comField.clear(); //Clear the textbox
}
Behold, the very simple and crude solution!
I believe your issue is with properly clearing the buffer. I found a line of code that goes through and clears each character, since it is a character array. There is theoretically no buffer to clear once it is read.
Use:
for(int i=0;i<UDP_TX_PACKET_MAX_SIZE;i++) packetBuffer[i] = 0;
Once you read the data, and that will clear the array. I also found out that when trying to do logic on the data that was received, in order to control some output, I needed to first convert the packetBuffer to a string. After that, all seemed to work correctly.
Hope that help.

sprintf() and WriteFile() affecting string Buffer

I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:
1) read a byte from the serial port
2) store each char into tagBuffer as they are read
3) run a query using tagBuffer to see what type of tag it is (book or shelf tag)
4) depending on the type of tag, output a series of bytes corresponding to the type of tag
Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.
The lines are the two lines at the very bottom:
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().
I thought sprintf and WriteFile are I/O functions and would have no effect on variables.
I'm stuck and I need help to fix this.
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// resets tagBuffer in case tagBuffer is out of sync
time_t t_time = time(0);
char buf[50];
if (HasOverlappedIoCompleted(&ovWrite))
{
i=0;
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
if( strlen(tagBuffer) >= PACKET_LENGTH )
{
i = 0;
}
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
sprintf(query,"select type from rfid where rfidnum=\"");
strcat(query, tagBuffer);
strcat(query, "\"");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
//process result and send back to handheld
res = mysql_use_result(&mysql);
while(row = mysql_fetch_row(res))
{
printf("result of query is %s\n",row[0]);
string str = "";
str = string(row[0]);
if( str == "book" )
{
WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else if ( str == "shelf" )
{
WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR),
&dwBytesWritten,&ovWrite);
}
else //this else doesn't work
{
WriteFile(hSerial,NOK,strlen(NOK),
&dwBytesWritten,&ovWrite);
}
}
mysql_free_result(res);
// Display a response to input
//printf("query is %s!\n", query);
//printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer));
//without these, tagBuffer only holds the last character
sprintf(buf,"%s!\n", tagBuffer);
WriteFile(hSerial,buf,strlen(buf), &dwBytesWritten,&ovWrite);
}
}
With those two lines, my output looks like this:
s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001
Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.
Any help at all will be greatly appreciated. Thanks.
Where are you allocating tagbuffer, how large is it?
It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.
It seems unlikely that those two lines would have that effect on a correct program - maybe you haven't allocated sufficient space in buf for the whole length of the string in tagBuffer? This might cause a buffer overrun that is disguising the real problem?
The first thing I'd say is a piece of general advice: bugs aren't always where you think they are. If you've got something going on that doesn't seem to make sense, it often means that your assumptions somewhere else are wrong.
Here, it does seem very unlikely that an sprintf() and a WriteFile() will change the state of the "buf" array variable. However, those two lines of test code do write to "hSerial", while your main loop also reads from "hSerial". That sounds like a recipie for changing the behaviour of your program.
Suggestion: Change your lines of debugging output to store the output somewhere else: to a dialog box, or to a log file, or similar. Debugging output should generally not go to files used in the core logic, as that's too likely to change how the core logic behaves.
In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:
Serial Port I/O from Joseph Newcomer's website.
Serial Communications in Win32 from MSDN.
In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.
This may sound more complex than your current design, but really it isn't, as Newcomer explains.
I hope this helps!