Sunday, June 19, 2016
Technetium-99m is a widely used radioactive tracer isotope in Nuclear Medicine. ...Technetium -99m is produced by bombarding molybdenum 98Mo with neutrons. The resultant 99Mo decays with a half-life of 66 hours to the metastable state of Tc . This process permits the production of 99mTc for medical purposes. Since 99Mo is a fission product of 235U fission, it can be separated from the other fission products and used to generate 99mTc. For medical purposes, the 99mTc is used in the form of pertechnate, TcO4-
Thursday, June 16, 2016
(becareful with bot on this link)
Coal Ash Is More Radioactive Than Nuclear Waste
By burning away all the pesky carbon and other impurities, coal power plants produce heaps of radiation
Coal, meanwhile, is believed responsible for a host of more quotidian problems, such as mining accidents, acid rain and greenhouse gas emissions. But it isn't supposed to spawn three-eyed fish like Blinky.
Over the past few decades, however, a series of studies has called these stereotypes into question. Among the surprising conclusions: the waste produced by coal plants is actually more radioactive than that generated by their nuclear counterparts. In fact, the fly ash emitted by a power plant—a by-product from burning coal for electricity—carries into the surrounding environment 100 times more radiation than a nuclear power plant producing the same amount of energy. * [See Editor's Note at end of page 2]
At issue is coal's content of uranium and thorium, both radioactive elements. They occur in such trace amounts in natural, or "whole," coal that they aren't a problem. But when coal is burned into fly ash, uranium and thorium are concentrated at up to 10 times their original levels
Nuclear Trafficking Hoaxes: A Short History of Scams Involving Red Mercury and Osmium-187
Multiple instances of profit-motivated nuclear hoaxes have been
reported in the media in the past two decades, in which sellers offer
weapons-usable or weapons-grade nuclear material and instead deliver
some other bogus radioactive, or in some cases, nonradioactive
substance. Such scams increased when economic conditions in the former
Soviet Union and Eastern Europe declined in the late 1980s and early
1990s. The region's economic decline coupled with weakened security and
enforcement mechanisms and a growing interest on the part of both state
and non-state actors to illegally obtain nuclear materials all created
favorable conditions for nuclear trafficking scams.
Nuclear scams often involve natural uranium, depleted uranium, or low-enriched uranium (LEU) reactor fuel, none of which is suitable for nuclear weapons. Other scams involve highly radioactive sources, such as cesium-237 or cobalt-60, which, though not fissile material, could be lethal components in a radiological dispersal device.
Two non-fissile substances that frequently have been used by con artists as substitutes for nuclear materials are so-called red mercury and osmium-187. Hoaxes involving both substances have become legendary after being the subject of widely reported trafficking attempts throughout the 1990s. A major reason these scams have been so widespread and common is likely related to the fact that there is some truth in the claims made by the con artists. Red mercury is the name given to an alleged nuclear weapon ingredient that does not exist in the form (Hg2Sb207) and with the characteristics described by nuclear scam artists. Some experts have suggested, however, that red mercury is in fact another name for lithium-6, a substance that can be used in the production of compact and highly efficient thermonuclear devices. Osmium-187 is a bona fide nonradioactive material not used for weapon construction, but because it is indeed an expensive commodity and one that is produced through a process similar to uranium enrichment, nuclear traffickers seized on it as a marketable product. This issue brief provides background on the two substances and summarizes some of the high-profile hoaxes in which they have been used.
References to red mercury began to appear in major Russian and Western media sources in the late 1980s and early 1990s. The articles were never specific as to what exactly red mercury was, but the accounts claimed that the substance was a valuable strategic commodity and a necessary component in a nuclear bomb and/or that it was important in the production of boosted nuclear weapons. Supposedly citing a leaked Russian government memorandum, an April 1993 article in the widely-read Russian daily Pravda reported that red mercury is "a super-conductive material used for producing high-precision conventional and nuclear bomb explosives, 'stealth' surfaces and self-guided warheads. Primary end-users are major aerospace and nuclear-industry companies in the United States and France along with nations aspiring to join the nuclear club, such as South Africa, Israel, Iran, Iraq, and Libya."[5] Red mercury was peddled throughout Europe and the Middle East by Russian businessmen, who made fortunes in the process. In one case, a Saudi Arabian sheikh reportedly paid £2.5 million for several shipments of the substance.[6] Described as a brownish powder or a red liquid,[7] red mercury was said to originate from various locations in the USSR, namely Ust-Kamenogorsk, Kazakhstan,[8] and Krasnoyarsk, Novosibirsk,[9] and Sverdlovsk in Russia.[10]
Western media also carried accounts of red mercury and its nuclear applications. According to a July 1993 article in Nucleonics Week, red mercury was a code word used in the USSR nuclear weapons program since the 1950s to describe enriched lithium-6, which, according to the article, can be used to produce tritium, which, when fused with deuterium, can be used in the fusion stage of a thermonuclear weapon. Lithium-6 received its code name because of the red-hued impurities in the mercury used to produce lithium-6. According to the article, the USSR built a large complex in the early days of its nuclear weapon program to produce and stockpile lithium-6.[11]
The Nucleonics Week article was followed by two television programs on red mercury produced by the British Broadcasting Corporation as part of its Dispatches series. Trail of Red Mercury (1993) and Pocket Neutron (1994) presented "startling new evidence" that Russian scientists had designed a simple, cheap, pure fusion weapon or neutron bomb, the size of a tennis ball, using a "mysterious compound" called red mercury.[12] A June 1994 article in the venerable International Defense Review quoted Western and Russian nuclear physicists as confirming the existence and destructive capabilities of red mercury.[13] One of those quoted, U.S. nuclear physicist Sam Cohen, to this day continues to write passionately about the nuclear applications of red mercury, which he describes as a "ballotechnic" explosive that, "when ignited, does not actually explode but stays intact long enough to produce the enormous temperatures and pressures sufficient to enable deuterium-tritium fusion."[14]
However, beginning in 1992, at the height of the red mercury scams, government and independent experts from Russia, the United States, and elsewhere made repeated attempts to debunk the idea that red mercury was a wonder-weapon. In September 1992, Yuriy Tychkov, deputy minister of the Russian Ministry of Atomic Energy and Industry, called rumors about red mercury's usefulness in weapons a sham. According to Tychkov, many entrepreneurs were using the name of red mercury, an uncontrolled substance, as a cover for smuggling controlled substances—precious metals and fissile material—out of the country. Tychkov reported that dozens of Russian ministries were inundated with requests for export licenses for the non-existent substance.[15] The head of Interpol's National Central Bureau in Russia, Militia Lieutenant General Vasiliy Ignatov, made the following statement at an Interpol congress in March 1993: "No red mercury exists in nature, either factually or physically, and such an element is impossible to create. What is being sold, as a rule, are different reagents."[16] In a July 1993 Pravda article, Major General Aleksandr Gurov, director of the Russian Security Ministry's Scientific Research Institute of Security was quoted as saying that red mercury is a slang term for "oxide of mercury."[17] Gurov was later appointed head of a special government commission tasked with investigating red mercury. In his findings, released in 1995, Gurov insisted that red mercury does not exist.[18]
One of the strangest chapters in the story of red mercury scams was the signing of Decree No. 75-RPS On the Promekologiya Concern on February 21, 1992 by then President Boris Yeltsin granting a Yekaterinburg-based company, Promekologiya, exclusive rights to produce, purchase, store, transport, and sell 84 tons of red mercury for $24.2 billion over a three-year period to a Van Nuys, California company called Automated Products International. Promekologiya was to use proceeds from the sales for public works projects throughout Russia, such as defense conversion, power generation, and environmental projects. The head of Promekologiya reported that his company received over $40 billion in orders from foreign companies.[19] The decree was later rescinded on March 20, 1993. Open source material does not indicate what materials, if any, actually changed hands.[20]
By the mid- to late-1990s, open source accounts of trafficking in red mercury in the former Soviet Union dried up as media and government authorities debunked its alleged nuclear applications and denied its very existence. Russian media carried fewer and fewer accounts of red mercury hoaxes as reporters, the public, and prospective buyers became better informed.
Political pundits and social commentators have advanced several theories to explain the 1990s red mercury phenomenon in the former Soviet Union. Some suggest that it was simply a grand deception perpetrated by entrepreneurial criminals meant to bilk money from gullible buyers. A more sinister interpretation, and one shared by Deputy Minister of Atomic Energy Tychkov, is that it was a cover for the successful export of precious metals or fissile material. Still others believe the phenomenon was a carefully crafted scam by the Russian government to make millions. A report by Intelligence Online suggests that Western intelligence agencies used the Russian-produced scam to identify middlemen caught in Russia's trap. Furthermore, the report claims that the United States has a renewed interest in reviewing the last decade's red mercury scams and its perpetrators to determine whether real radioactive material actually exchanged hands.[21]
Others, however, continue to believe in red mercury and its purported nuclear properties. U.S. nuclear physicist Sam Cohen continues to claim that the U.S. government is simply turning a blind eye to a technology it knows exists and raises concerns about the consequences of a terrorist attack using a red mercury device.[22] Two Russian academics go so far as to claim that red mercury can be used to resolve the ills of the human race and planet earth by aiding in oil extraction, restoring exhausted mines to production, reviving unproductive agricultural land, recultivating nuclear test sites, cleansing land polluted with radionuclides, producing medicine, and creating environmentally clean fuel for new sources of energy.[23]
Osmium is a hard metal of the platinum group used to produce very hard alloys for fountain pen tips, instrument pivots, phonograph needles, and electrical contacts.[24] Osmium-related scams involve osmium-187, one of the seven naturally occurring osmium isotopes, which comprises only 1.64% of natural osmium. Osmium-187 is included neither in special nuclear materials, which are controlled by the U.S. Nuclear Regulatory Commission, nor in the dual-use items of the Commerce Control List maintained by the Bureau of Industry and Security of the U.S. Department of Commerce.[25] Osmium-187 is not a controlled material under the Guidelines of the Nuclear Suppliers Group (NSG) either. Osmium-187 is frequently used in scams by con artists, however, who claim that it has nuclear weapons applications.
Because osmium-187 is very dense, it might be thought to be an excellent material for a nuclear weapon's tamper, which allows the nuclear explosive material to stay compact for a relatively long period of time, increasing the explosive yield. However, osmium-187 would not be a logical choice for a tamper because it is very expensive, costing from $50,000 to $100,000 per gram, and other materials, such as uranium-238, are much cheaper and more readily available. In addition, osmium-187 would be too dense to be used as a neutron reflector, which aids in increasing the yield of a nuclear weapon. Instead, beryllium, a lighter material, is typically used to make reflectors because it is less expensive and has better neutron reflecting properties. Finally, osmium-187 is not radioactive, which excludes its use as a component of a "dirty bomb," or radiological dispersal device.
The technique required to separate osmium-187 from natural osmium is quite similar to the uranium enrichment process, which could be one of the arguments used by con artists to claim the isotope has nuclear applications. Such arguments are frequently repeated by the media as well, which unfortunately give credence to the con artists' claims that the isotope indeed has nuclear applications. For example, a September 2002 article in the Russian newspaper Argumenty i fakty discusses the threat posed by smuggling of osmium-187, claiming that technologies for the chemical separation of osmium and plutonium are completely identical, erroneously implying that osmium is linked to the production of nuclear weapons.[26]
In spite of attempts by experts to debunk osmium's supposed nuclear applications, many sources, including the media and even government officials, continue to tout osmium's strategic significance and warn of its possible use in nuclear weapons. For example, in September 2002, a member of the Russian Parliament's Security Committee, Viktor Ilyukhin, accused Kazakhstan of unauthorized production of osmium-187, which, in his words, can be used in the production of nuclear weapons.[27] It's also notable that Kazakhstan itself controls osmium-187 as a dual-use material.[28]
Scams related to osmium-187 trafficking are generally motivated by profit and usually occur on the territory of the former Soviet Union, since the region possesses two major osmium mining plants: Norilsk Nickel in Russia and Kazakhmys in Kazakhstan.[29] Some examples of attempted trafficking scams involving osmium-187 include the following:
Nuclear scams often involve natural uranium, depleted uranium, or low-enriched uranium (LEU) reactor fuel, none of which is suitable for nuclear weapons. Other scams involve highly radioactive sources, such as cesium-237 or cobalt-60, which, though not fissile material, could be lethal components in a radiological dispersal device.
Two non-fissile substances that frequently have been used by con artists as substitutes for nuclear materials are so-called red mercury and osmium-187. Hoaxes involving both substances have become legendary after being the subject of widely reported trafficking attempts throughout the 1990s. A major reason these scams have been so widespread and common is likely related to the fact that there is some truth in the claims made by the con artists. Red mercury is the name given to an alleged nuclear weapon ingredient that does not exist in the form (Hg2Sb207) and with the characteristics described by nuclear scam artists. Some experts have suggested, however, that red mercury is in fact another name for lithium-6, a substance that can be used in the production of compact and highly efficient thermonuclear devices. Osmium-187 is a bona fide nonradioactive material not used for weapon construction, but because it is indeed an expensive commodity and one that is produced through a process similar to uranium enrichment, nuclear traffickers seized on it as a marketable product. This issue brief provides background on the two substances and summarizes some of the high-profile hoaxes in which they have been used.
Red Mercury
Red mercury has been the subject of dozens, if not hundreds, of cases or attempted cases of illicit trafficking. Some of the more interesting cases involving the transfer of materials under the name of red mercury include the following:- After his defection, a former deputy unit chief of the North Korean uranium refinery plant Namchon Chemical Complex claimed that North Korea imported beryllium and red mercury from sources in Russia in 1993 through a smuggling organization in Pyongyang that involved the Russian mafia.[1]
- In one attempt that stands out for the quantity offered and price requested, a Romanian woman reportedly offered to sell 138 kg of red mercury purchased in Chelyabinsk and acquired in Moscow to the Swiss firm Mueller Troihand for $340,000 per kg.[2]
- A December 1997 New York Times article reported allegations made by a political rival that former Bosnian Serb leader Radovan Karadzic attempted to purchase a nuclear weapon in 1995 from sources in the former Soviet Union in order to put an end to the Bosnian War. Karadzic allegedly paid $6 million up front for the device, with an additional $60 million to follow. Told that the device was made from red mercury, Karadzic received a brass container filled with jelly-like material. Surprised at the contents, he reportedly sent aides to Moscow to determine whether the device was in fact a nuclear weapon. To his dismay, the word from Moscow was that he had been swindled.[3]
- A June 1999 issue of Jane's Intelligence Review cited Western intelligence analysts as saying that al-Qai'da operatives with little technical expertise were being swindled in their attempts to locate and purchase nuclear materials. One of these agents, later arrested in the United States, may have been swindled by con artists selling red mercury.[4]
References to red mercury began to appear in major Russian and Western media sources in the late 1980s and early 1990s. The articles were never specific as to what exactly red mercury was, but the accounts claimed that the substance was a valuable strategic commodity and a necessary component in a nuclear bomb and/or that it was important in the production of boosted nuclear weapons. Supposedly citing a leaked Russian government memorandum, an April 1993 article in the widely-read Russian daily Pravda reported that red mercury is "a super-conductive material used for producing high-precision conventional and nuclear bomb explosives, 'stealth' surfaces and self-guided warheads. Primary end-users are major aerospace and nuclear-industry companies in the United States and France along with nations aspiring to join the nuclear club, such as South Africa, Israel, Iran, Iraq, and Libya."[5] Red mercury was peddled throughout Europe and the Middle East by Russian businessmen, who made fortunes in the process. In one case, a Saudi Arabian sheikh reportedly paid £2.5 million for several shipments of the substance.[6] Described as a brownish powder or a red liquid,[7] red mercury was said to originate from various locations in the USSR, namely Ust-Kamenogorsk, Kazakhstan,[8] and Krasnoyarsk, Novosibirsk,[9] and Sverdlovsk in Russia.[10]
Western media also carried accounts of red mercury and its nuclear applications. According to a July 1993 article in Nucleonics Week, red mercury was a code word used in the USSR nuclear weapons program since the 1950s to describe enriched lithium-6, which, according to the article, can be used to produce tritium, which, when fused with deuterium, can be used in the fusion stage of a thermonuclear weapon. Lithium-6 received its code name because of the red-hued impurities in the mercury used to produce lithium-6. According to the article, the USSR built a large complex in the early days of its nuclear weapon program to produce and stockpile lithium-6.[11]
The Nucleonics Week article was followed by two television programs on red mercury produced by the British Broadcasting Corporation as part of its Dispatches series. Trail of Red Mercury (1993) and Pocket Neutron (1994) presented "startling new evidence" that Russian scientists had designed a simple, cheap, pure fusion weapon or neutron bomb, the size of a tennis ball, using a "mysterious compound" called red mercury.[12] A June 1994 article in the venerable International Defense Review quoted Western and Russian nuclear physicists as confirming the existence and destructive capabilities of red mercury.[13] One of those quoted, U.S. nuclear physicist Sam Cohen, to this day continues to write passionately about the nuclear applications of red mercury, which he describes as a "ballotechnic" explosive that, "when ignited, does not actually explode but stays intact long enough to produce the enormous temperatures and pressures sufficient to enable deuterium-tritium fusion."[14]
However, beginning in 1992, at the height of the red mercury scams, government and independent experts from Russia, the United States, and elsewhere made repeated attempts to debunk the idea that red mercury was a wonder-weapon. In September 1992, Yuriy Tychkov, deputy minister of the Russian Ministry of Atomic Energy and Industry, called rumors about red mercury's usefulness in weapons a sham. According to Tychkov, many entrepreneurs were using the name of red mercury, an uncontrolled substance, as a cover for smuggling controlled substances—precious metals and fissile material—out of the country. Tychkov reported that dozens of Russian ministries were inundated with requests for export licenses for the non-existent substance.[15] The head of Interpol's National Central Bureau in Russia, Militia Lieutenant General Vasiliy Ignatov, made the following statement at an Interpol congress in March 1993: "No red mercury exists in nature, either factually or physically, and such an element is impossible to create. What is being sold, as a rule, are different reagents."[16] In a July 1993 Pravda article, Major General Aleksandr Gurov, director of the Russian Security Ministry's Scientific Research Institute of Security was quoted as saying that red mercury is a slang term for "oxide of mercury."[17] Gurov was later appointed head of a special government commission tasked with investigating red mercury. In his findings, released in 1995, Gurov insisted that red mercury does not exist.[18]
One of the strangest chapters in the story of red mercury scams was the signing of Decree No. 75-RPS On the Promekologiya Concern on February 21, 1992 by then President Boris Yeltsin granting a Yekaterinburg-based company, Promekologiya, exclusive rights to produce, purchase, store, transport, and sell 84 tons of red mercury for $24.2 billion over a three-year period to a Van Nuys, California company called Automated Products International. Promekologiya was to use proceeds from the sales for public works projects throughout Russia, such as defense conversion, power generation, and environmental projects. The head of Promekologiya reported that his company received over $40 billion in orders from foreign companies.[19] The decree was later rescinded on March 20, 1993. Open source material does not indicate what materials, if any, actually changed hands.[20]
By the mid- to late-1990s, open source accounts of trafficking in red mercury in the former Soviet Union dried up as media and government authorities debunked its alleged nuclear applications and denied its very existence. Russian media carried fewer and fewer accounts of red mercury hoaxes as reporters, the public, and prospective buyers became better informed.
Political pundits and social commentators have advanced several theories to explain the 1990s red mercury phenomenon in the former Soviet Union. Some suggest that it was simply a grand deception perpetrated by entrepreneurial criminals meant to bilk money from gullible buyers. A more sinister interpretation, and one shared by Deputy Minister of Atomic Energy Tychkov, is that it was a cover for the successful export of precious metals or fissile material. Still others believe the phenomenon was a carefully crafted scam by the Russian government to make millions. A report by Intelligence Online suggests that Western intelligence agencies used the Russian-produced scam to identify middlemen caught in Russia's trap. Furthermore, the report claims that the United States has a renewed interest in reviewing the last decade's red mercury scams and its perpetrators to determine whether real radioactive material actually exchanged hands.[21]
Others, however, continue to believe in red mercury and its purported nuclear properties. U.S. nuclear physicist Sam Cohen continues to claim that the U.S. government is simply turning a blind eye to a technology it knows exists and raises concerns about the consequences of a terrorist attack using a red mercury device.[22] Two Russian academics go so far as to claim that red mercury can be used to resolve the ills of the human race and planet earth by aiding in oil extraction, restoring exhausted mines to production, reviving unproductive agricultural land, recultivating nuclear test sites, cleansing land polluted with radionuclides, producing medicine, and creating environmentally clean fuel for new sources of energy.[23]
Osmium-187
No sooner had red mercury begun to disappear from media reports than nuclear traffickers began touting a new commodity—osmium-187—as a vital substance for the creation of nuclear weapons.Osmium is a hard metal of the platinum group used to produce very hard alloys for fountain pen tips, instrument pivots, phonograph needles, and electrical contacts.[24] Osmium-related scams involve osmium-187, one of the seven naturally occurring osmium isotopes, which comprises only 1.64% of natural osmium. Osmium-187 is included neither in special nuclear materials, which are controlled by the U.S. Nuclear Regulatory Commission, nor in the dual-use items of the Commerce Control List maintained by the Bureau of Industry and Security of the U.S. Department of Commerce.[25] Osmium-187 is not a controlled material under the Guidelines of the Nuclear Suppliers Group (NSG) either. Osmium-187 is frequently used in scams by con artists, however, who claim that it has nuclear weapons applications.
Because osmium-187 is very dense, it might be thought to be an excellent material for a nuclear weapon's tamper, which allows the nuclear explosive material to stay compact for a relatively long period of time, increasing the explosive yield. However, osmium-187 would not be a logical choice for a tamper because it is very expensive, costing from $50,000 to $100,000 per gram, and other materials, such as uranium-238, are much cheaper and more readily available. In addition, osmium-187 would be too dense to be used as a neutron reflector, which aids in increasing the yield of a nuclear weapon. Instead, beryllium, a lighter material, is typically used to make reflectors because it is less expensive and has better neutron reflecting properties. Finally, osmium-187 is not radioactive, which excludes its use as a component of a "dirty bomb," or radiological dispersal device.
The technique required to separate osmium-187 from natural osmium is quite similar to the uranium enrichment process, which could be one of the arguments used by con artists to claim the isotope has nuclear applications. Such arguments are frequently repeated by the media as well, which unfortunately give credence to the con artists' claims that the isotope indeed has nuclear applications. For example, a September 2002 article in the Russian newspaper Argumenty i fakty discusses the threat posed by smuggling of osmium-187, claiming that technologies for the chemical separation of osmium and plutonium are completely identical, erroneously implying that osmium is linked to the production of nuclear weapons.[26]
In spite of attempts by experts to debunk osmium's supposed nuclear applications, many sources, including the media and even government officials, continue to tout osmium's strategic significance and warn of its possible use in nuclear weapons. For example, in September 2002, a member of the Russian Parliament's Security Committee, Viktor Ilyukhin, accused Kazakhstan of unauthorized production of osmium-187, which, in his words, can be used in the production of nuclear weapons.[27] It's also notable that Kazakhstan itself controls osmium-187 as a dual-use material.[28]
Scams related to osmium-187 trafficking are generally motivated by profit and usually occur on the territory of the former Soviet Union, since the region possesses two major osmium mining plants: Norilsk Nickel in Russia and Kazakhmys in Kazakhstan.[29] Some examples of attempted trafficking scams involving osmium-187 include the following:
- On June 21, 2000, police in Novosibirsk Oblast, Russia, arrested eight suspects and seized an ampoule with an unspecified quantity of osmium-187. The material was stolen from a Kazakhstani factory by four workers, who had transported it across the border into Russia in hopes of selling it in Novosibirsk.[30]
- According to the Moscow regional directorate of the Russian Federal Security Service, on December 28, 2001, five suspects were arrested in Moscow for attempting to sell 6 grams of osmium-187 to a Moscow banker for $800,000.[31] On February 28, 2003, Russia's Federal Security Service announced that it had thwarted a criminal gang's attempts to sell osmium-187 when security officers detained one person with an unspecified amount of osmium-187 in the Siberian city of Omsk.[32]
- http://www.nti.org/analysis/articles/nuclear-trafficking-hoaxes/
Tuesday, June 14, 2016
Building a Poker Bot: String and Number Recognition
This is the second part of Building a Poker Bot series where I describe my experience developing bot software
to play in online poker rooms. I'm building the bot with .NET framework and F# language which makes the task relatively
easy and very enjoyable. Here is the first part:
Building a Poker Bot: Card Recognition

We know our fixed regions where our labels are located, so we take those regions for processing:

For each region we trim away the blank margins around the text (i.e. left, top, right and bottom padding):

We find dark lines between bright symbols and we consider them as gaps between characters:

The final step is to compare each symbol to the known patterns and find the best match (in case of my layout the match for symbols is always 100% perfect). Let's look how these steps are implemented.
http://mikhail.io/2016/02/building-a-poker-bot-string-recognition/
Why string recognition
Reading cards and other fixed images was the first step. The bot should also be able to read different text-based information from the screen, e.g.- Current blind levels
- Current pot size
- The size of bets made by each player
- Player names
- Stack sizes
- Chat messages (for advanced scenarios)
New challenges
String recognition has some specific difficulties when compared to fixed images like cards:- The size of a string is not predefined. Obviously, the longer the string, the more space it takes on the screen
- The position of a string is not fixed either. Some strings are aligned to the center, others may diverge based on other variable parts like stakes or blinds
- Different strings might be rendered in different font size
- Pick the layout which makes your life easier
- Adjust fonts and positions if possible
- Make sure that all important strings are always visible and not overlapping to other information
- For each string define a region where it belongs to in 100% cases. The background of this region should be more or less evenly filled with a color in contrast to the font color.
String recognition steps
We start with a screenshot of a poker table again:We know our fixed regions where our labels are located, so we take those regions for processing:
For each region we trim away the blank margins around the text (i.e. left, top, right and bottom padding):
We find dark lines between bright symbols and we consider them as gaps between characters:
The final step is to compare each symbol to the known patterns and find the best match (in case of my layout the match for symbols is always 100% perfect). Let's look how these steps are implemented.
Removing padding around the text
Because the padding is removed from all 4 sides of the region, I decided to useArray2D
data type to be able to iterate in different order. The whole algorithm operates
with black or white points defined as a helper type:type BW = B | W
So the removePadding
function has type of BW[,] -> BW[,]
and looks
like this:let removePadding pixels =
let allBlack s = Seq.exists ((=) W) s
let maxWidth = Array2D.length1 pixels - 1
let maxHeight = Array2D.length2 pixels - 1
let firstX = [0..maxWidth]
|> Seq.tryFindIndex (fun y -> allBlack pixels.[y, 0..maxHeight])
let lastX = [0..maxWidth]
|> Seq.tryFindIndexBack (fun y -> allBlack pixels.[y, 0..maxHeight])
let firstY = [0..maxHeight]
|> Seq.tryFindIndex (fun x -> allBlack pixels.[0..maxWidth, x])
let lastY = [0..maxHeight]
|> Seq.tryFindIndexBack (fun x -> allBlack pixels.[0..maxWidth, x])
match (firstX, lastX, firstY, lastY) with
| (Some fx, Some lx, Some fy, Some ly) -> pixels.[fx..lx, fy..ly]
| _ -> Array2D.init 0 0 (fun _ _ -> B)
The first part finds the amount of fully-black columns and rows in the array.
Then, if white points are found, the second part returns a sub array based on
the indices, otherwise empty array is returned.Split the text into characters
First, we convert our 2D array into the list of lists, where each item in the top-level list represents a single column of pixels:let pixelColumns =
[0..Array2D.length1 pixels - 1]
|> Seq.map (fun x -> pixels.[x, 0..Array2D.length2 pixels - 1] |> List.ofArray)
Then we can fold this list of columns into the symbols, where each symbol itself
is the list of columns:let splitIntoSymbols (e : BW list) (state: BW list list list) =
match state with
| cur::rest ->
if isSeparator e then
match cur with
| _::_ -> []::state // add new list
| _ -> state // skip if we already have empty item
else (e::cur)::rest // add e to current list
| _ -> [[e]]
Seq.foldBack splitIntoSymbols pixelColumns []
The type of state
is a bit of brain teaser, I guess it could be improved
by introducing some intermediate type with descriptive name, but I decided
to leave that part for now. Read it as list of symbols, which are lists of
columns, which are lists of pixels.Match the symbols vs the known patterns
This part was already described in my first article. Basically we compare the list of black or white points to the patterns of the known symbols:let getChar patterns bws =
let samePatterns h p =
Seq.zip h p
|> Seq.forall (fun (v1, v2) -> v1 = v2)
let matchingPattern =
patterns
|> Array.filter (fun p -> List.length p.Pattern = List.length bws)
|> Array.filter (fun p -> samePatterns bws p.Pattern)
|> Array.tryHead
defaultArg (Option.map (fun p -> p.Char) matchingPattern) '?'
Putting it all together
TherecognizeString
function accepts lower-order functions to match
symbols and get pixels together with width and height of the region:recognizeString: (BW list list -> char) -> (int -> int -> color) -> int -> int -> string
It builds an array of pixels, removes padding and folds with recognition.let recognizeString matchSymbol getPixel width height =
let pixels =
Array2D.init width height (fun x y -> isWhite (getPixel x y))
|> removePadding
let pixelColumns =
[0..Array2D.length1 pixels - 1]
|> Seq.map (fun x -> pixels.[x, 0..Array2D.length2 pixels - 1] |> List.ofArray)
Seq.foldBack splitIntoSymbols pixelColumns []
|> List.map matchSymbol
|> Array.ofSeq
|> String.Concat
Then we use it with a specific recognition patterns, e.g. known digits in case
of numbers recognition:let recognizeNumber x =
recognizeString (getChar numberPatterns) x
A way to produce these patterns is discussed in the previous part.Conclusion
String recognition takes a bit more steps to execute comparing to the recognition of fixed objects. Nevertheless it's pretty straightforward to implement once we split it into small and well-understood conversion steps. The full code for card recognition can be found in my github repo.http://mikhail.io/2016/02/building-a-poker-bot-string-recognition/
Security breaches
Title: twin hantu's login trojan horse Machine: burro.monkeybrains.net OS: Linux 2.1? URLs: 1. http://www.sans.org/y2k/050900-1500.htm 2. http://staff.washington.edu/dittrich/misc/trinoo.analysis Summary (notes taken during comprimise analysis):
- The machine is comprimised (portmap?? -- still unsure how initial breach is made).
- A 'twin' user is created with UID=0 and HOME=/.
- A 'hantu' user is created and then erased
- The 'twin' line is edited out of the /etc/passwd file with pico.
- The /etc/shadow retains the 'twin' user.
- The target machines 'login' is replaced with a trojan horse.
- This Trojan horse allows root access for incoming telnets with a specific term setting. This vt number can be found by doing a 'srtings login | grep vt'
- A UDP controlled server named 'ns' is installed (a ps -aux reveals a ./ns). This client sends a *HELLO* packet when started up to a client (it's IP is availible from a 'strings ns'). The ns on burro was installed in /daemon/ns). This is how I was alerted to burro's infection: burro was ping flooding other machines on the internet with this 'ns' client. (Please see url #2 above
- The attacker leaves behind a .bash_history file which reveals several more tid-bits.
1) The ftp host which houses the 'bj.c' which is compiled to make the trojan login.
2) Other machines the user leap frogs to from your machine. All you have to do is set term=vt???? where ???? indicates a number from 1000-9999 and you too can access other compromised machines.
3) Most commands are issued through a client side script. 'twin' doesn't really know Unix.
4) Of course, this .bash_history file could be a plant, but I'm leaning toward a not-too-bright user senario. - More informaion is found in other system log files (eg originating IPs for telnets)
Time to reformat that machine with FreeBSD!!!(I hope rk is friendly hehehe)
Another breakin this week... at a place I contracted at for a few hours. They too were running Linux. I patched up all the messed up binaries with new rpm... More info
Here are the people (and bots) who have looked at this page: gunzip -c /www/logs/archive/access-www.monkeybrains.net.gz | grep ' /security' | awk '{print $1}' | sort -u | nslookup | grep Name: *** lala.monkeybrains.net can't find 208.37.12.165: Non-existent host/domain *** lala.monkeybrains.net can't find 208.48.124.4: Server failed *** lala.monkeybrains.net can't find 212.150.51.90: Non-existent host/domain *** lala.monkeybrains.net can't find 216.34.109.191: Non-existent host/domain *** lala.monkeybrains.net can't find 216.34.109.192: Non-existent host/domain Name: ras-c5800-1-49-73.dialup.wisc.edu Name: kremlin.cs.uidaho.edu Name: mail.skynet.gr Name: ss06.ny.us.ibm.com Name: ss11.ny.us.ibm.com Name: AKCF1.xtra.co.nz Name: aspseek.swusa.com Name: 208.184.110.33.svwh.net Name: marvin.northernlight.com Name: lb1.antarcti.ca Name: j6000.inktomi.com Name: cr032r01.bos2.fastsearch.net Name: router-sj.atomz.com Name: gw03.webtop.com Name: gw04.webtop.com Name: www.britton-gw-uk.proteusweb.com Name: adsl-216-103-213-34.dsl.snfc21.pacbell.net Name: dhcp-197.sf.bmarts.com Name: www.ip3000.com Name: www.ip3000.com Name: d83b38fc.dsl.flashcom.net Name: adsl-63-203-32-98.dsl.snfc21.pacbell.net Name: adsl-63-203-75-141.dsl.snfc21.pacbell.net Name: crawler3.googlebot.com Name: crawler1.googlebot.com Name: crawler2.googlebot.com Name: router-sc.atomz.com
This page was created to keep track of security breaches on the MonkeyBrains network.
https://www.monkeybrains.net/security/
Monday, June 13, 2016
with what? you ask...with this tricky chit to their reverse poison:
Really, what I am trying to accomplish in the client is
1) Subscribe to channel XYZ normally, with attached callbacks, etc
2) Construct a well-formed JSON message that would be similar to one
normally received by XYZ, but instead it was formed by the client
3) Send the message through the normal WebSync message-received
functions, which ultimately will call the originally attached
callbacks as if it had been a normal message
My use case here is that I am getting data from a WebSocket connection
(non WebSync) that is forming JSON messages in the same format as
would normally be processed by WebSync. And instead of parsing the
messages myself and determining the correct callbacks based on the
channel, just pass it off to your wonderfully written JavaScript
client library that already does this sort of heavy lifting :).
I don't need to actually publish the message to the server because
this data is coming from another source, and would be for all
subscribers (in my case, using websockets because the data is *very*
high frequency, and necessitates low latency).
Speaking of which - are WebSockets still on your roadmap? I know that
they were pulled out of the HTML5 spec and instead put into their own
specification. And I also know that while WebSockets are supported in
*some* browsers, they are not in all (of the major ones, that is), and
FF4 will have them disabled by default
https://support.frozenmountain.com/hc/en-us/community/posts/200235809-Manually-send-message-through-event-loop
1) Subscribe to channel XYZ normally, with attached callbacks, etc
2) Construct a well-formed JSON message that would be similar to one
normally received by XYZ, but instead it was formed by the client
3) Send the message through the normal WebSync message-received
functions, which ultimately will call the originally attached
callbacks as if it had been a normal message
My use case here is that I am getting data from a WebSocket connection
(non WebSync) that is forming JSON messages in the same format as
would normally be processed by WebSync. And instead of parsing the
messages myself and determining the correct callbacks based on the
channel, just pass it off to your wonderfully written JavaScript
client library that already does this sort of heavy lifting :).
I don't need to actually publish the message to the server because
this data is coming from another source, and would be for all
subscribers (in my case, using websockets because the data is *very*
high frequency, and necessitates low latency).
Speaking of which - are WebSockets still on your roadmap? I know that
they were pulled out of the HTML5 spec and instead put into their own
specification. And I also know that while WebSockets are supported in
*some* browsers, they are not in all (of the major ones, that is), and
FF4 will have them disabled by default
https://support.frozenmountain.com/hc/en-us/community/posts/200235809-Manually-send-message-through-event-loop
AND WHY NOT DEACTIVATE THE SERVER (lm) HASH ?
Disable Storage of the LM Hash
So what’s wrong with the LM hash? Lets look at exactly how the LM hash is computed, via Wikipedia:
- The user’s ASCII password is converted to uppercase.
- This password is null-padded to 14 bytes.
- The “fixed-length” password is split into two 7-byte halves.
- These values are used to create two DES keys, one from each 7-byte half, by converting the seven bytes into a bit stream, and inserting a null bit after every seven bits (so 1010100 becomes 01010100). This generates the 64 bits needed for a DES key. (A DES key ostensibly consists of 64 bits; however, only 56 of these are actually used by the algorithm. The null bits added in this step are later discarded.)
- Each of the two keys is used to DES-encrypt the constant ASCII string “KGS!@#$%”, resulting in two 8-byte ciphertext values. The DES CipherMode should Set to ECB, and PaddingMode should set to NONE.
- These two ciphertext values are concatenated to form a 16-byte value, which is the LM hash.
- The password is first converted to all uppercase.
- The password is split into 2 different 7 byte chunks, which can be attacked separately.
Thankfully disabling the LM hash isn’t that hard. On your domain controller navigate to Start>Administrative Tools>Group Policy Editor>Computer Configurations>Windows Settings>Security Settings>Local Policies>Security Options. From here Scroll down to the “Network security: Do not store LAN Manager hash value on next reboot” setting and set it to Enabled.

Caveat emptor: although you’ve disabled the storage of the LM hashes, it doesn’t actually take place until users next change their password. If passwords aren’t changed after this setting is enforced, this is a moot point. I’ve seen environments that have this setting enabled but 90% of their passwords are still stored as LM because passwords are set to never expire, and users are never required to change their password. Once this setting is enabled, it’s not a bad idea to force a domain wide password reset.
Here's another question, how to gain access to usb ports which are blocked by the server and physical disabled
Contents
Overview
This page describes various ways of accessing hardware devices on Lazarus. These devices include, but are not limited to: ISA, PCI, USB, parallel port, serial port.Uniform multi-platform access to hardware devices is not implemented by the Free Pascal Runtime Library (RTL) or by the LCL - the underlying operating systems are often different enough to make that very difficult. Therefore, this article will basically cover hardware access methods on different platforms. The code can be compiled on different environments using conditional compiles, like this:
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
{$IFDEF WIN32}
Windows;
{$ENDIF}
{$IFDEF Unix}
ports;
{$ENDIF}
Parallel and Serial Comparison
ISA Cards, PCI Cards and the Parallel Port communicate with the computer using a parallel protocol. The Serial Port and USB devices work with a serial protocol. Because the processor and thus programming languages all work on a parallel approach to data, access to this kinds of protocols is easier to be implemented on the software side. When you access an Integer variable, for example, you can access it's value with a single command. With a serial protocol, however, you can only know one bit at a time, and you need to glue the pieces together to understand the data.Serial communication is difficult to be implemented directly, but it can be pretty easy if you use a pre-made component. It is also harder on the hardware side, so many devices use specialised Integrated Circuits or even Microcontrolers to implement it.
Now a brief comparison of hardware access protocols will be given:
|
Speed | Hardware implementation difficulty |
---|---|---|
Serial Port | Very slow (< E5 bit/s) | Medium |
Parallel Port | Slow (~ E6 bit/s) | Easy |
ISA Card | Medium (~ E7 bit/s) | Medium |
USB | Medium (~ E7 bit/s) | Hard |
PCI Card | Very Fast (> E9 bit/s) | Very Hard |
Parallel Communication
Using inpout32.dll for Windows
Windows has different ways to access hardware devices on the 9x series and on the NT series. On the 9x series (95, 98, Me) programs can access the hardware directly, just like they did on DOS. The NT series (Windows NT and XP), however, don't allow this approach. On this architecture, all communication with hardware ports must be through a device driver. This is a security mechanism, but developing a driver can cost too much in terms of time and money for small projects.Happily there is a library that solves this problem. If Windows NT is detected, it decompresses HWInterface.sys kernel device driver and installs it. If Windows 9x is detected, it simply uses assembler opcodes to access the hardware.
But how do I use the library? Simple! It has only two functions, Inp32 and Out32, and their use is quite intuitive.
We will load the library dynamically, so let's define both functions first:
type
TInp32 = function(Address: SmallInt): SmallInt; stdcall;
TOut32 = procedure(Address: SmallInt; Data: SmallInt); stdcall;
- Address represents the address of the port you desire to access
- Out32 sends Data to the port you specify by Address
- Inp32 returns a byte from the port you specify by Address
uses
....dynlibs...
type
TMyForm = class(TForm)
.........
private
{ private declarations }
Inpout32: THandle;
Inp32: TInp32;
Out32: TOut32;
.........
implementation
.........
procedure TMyForm.FormCreate(Sender: TObject);
begin
{$IFDEF WIN32}
Inpout32 := LoadLibrary('inpout32.dll');
if (Inpout32 <> 0) then
begin
// needs overtyping, plain Delphi's @Inp32 = GetProc... leads to compile errors
Inp32 := TInp32(GetProcAddress(Inpout32, 'Inp32'));
if (@Inp32 = nil) then Caption := 'Error';
Out32 := TOut32(GetProcAddress(Inpout32, 'Out32'));
if (@Out32 = nil) then Caption := 'Error';
end
else Caption := 'Error';
{$ENDIF}
end;
procedure TMyForm.FormDestroy(Sender: TObject);
begin
{$IFDEF WIN32}
FreeLibrary(Inpout32);
{$ENDIF}
end;
{$IFDEF WIN32}
myLabel.Caption := IntToStr(Inp32($0220));
{$ENDIF}
Note: For
deployment you need to include "inpout32.dll" in the same directory of
our application. Also library have to be registered in system using
administrator user on Windows NT/XP/2000 or elevated privileges on
Windows Vista/7. This can be done by installation program such
InnoSetup:
Filename: {sys}\rundll32.exe; Parameters: "inpout32.dll,IsInpOutDriverOpen"; WorkingDir: {app}; Flags: 32bit;
This is the homepage for the library: www.logix4u.net/inpout32.htm *see discussion*
Using assembler on Windows 9x
On Windows 9x you can also use assembler code. Suppose you wish to write $CC to the $320 port. The following code will do it: {$ASMMODE ATT}
...
asm
movl $0x320, %edx
movb $0xCC, %al
outb %al, %dx
end ['EAX','EDX'];
Troubleshooting on Windows
One possible source of trouble using parallel hardware that does not support Plug And Play on Windows is that Windows may assign the port utilized by your hardware to another device. You can find instructions on the URL below about how to tell Windows not to assign the address of your device to Plug And Play devices:http://support.microsoft.com/kb/135168
Using ioperm to access ports on Linux
The best way to access the hardware on Linux is through device drivers, but, due to the complexity of the task of creating a driver, sometimes a quick method is very useful.In order to use the "ports" unit under Linux your program must be run as root, and IOPerm must be called to set appropriate permissions on the port access. You can find documentation about the "ports" unit here.
The first thing to do is link to (g)libc and call IOPerm. A unit that links to the entire (g)libc exists on free pascal, but this unit gives problems when used directly by application and linking statically to the entire (g)libc library is not a very good idea because it changes often between version in an incompatible manner. Functions like ioperm, however, are unlikely to change.
{$IFDEF Linux}
function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external 'libc';
{$ENDIF}
- "from" represents the first port to be accessed.
- "num" is the number of ports after the first to be accessed, so ioperm($220, 8, 1) will give access for the program for all ports between and including $220 and $227.
{$IFDEF Linux}
i := ioperm($220, 8, 1);
port[$220] := $00;
myLabel.Caption := 'ioperm: ' + IntToStr(i);
i := Integer(port[$220]);
myOtherLabel.Caption := 'response: ' + IntToStr(i);
{$ENDIF}
General UNIX Hardware Access
{$IFDEF Unix}
Uses Clib; // retrieve libc library name.
{$ENDIF}
{$IFDEF Unix}
function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external clib;
{$ENDIF}
Note that FPC provides an abstraction for ioperm called "fpioperm" in unit x86, and also defines fpIOPL and out-/inport functions. These functions are currently implemented for Linux/x86 and FreeBSD/x86.
It is not recommended to link to libc unless absolutely necessary due to possible deployment and portability functions. Also manual linking to libc (by declaring ad hoc libc imports for functions that are available elsewhere) like done above is not recommended (e.g. the above libc import line will unnecessarily fail if the standard C lib is not called libc, like e.g. libroot on BeOS, or on platforms with a non standard C symbol mangling).
Note 2 Using unit libc is not recommended under any circumstances other than Kylix compatibility. See libc unit
Status and control
Besides data lines, the parallel port also has status and control lines which are accessed using the status and control registers. While the base address accesses the data lines and reads or writes data bytes from/to them, the Status register is accessed on the address offset by +1 and Control register is accessed on the offset +2. For example, LPT1 (first parallel port on a PC) has the base address $378, so its Status register is at $379 and Control register at $380. To get individual status line states, you read a byte from its address and its bits represent those lines. Setting control lines is similarly done by writing a byte with accordingly set bits to the Control register.Newer bidirectional parallel port versions have more registers on higher offsets. More details about them, together with information which bits map to which lines can be found here.
Most directly accessed hardware devices other than PC parallel ports are controlled in a similar way. Depending on the device in question, it is necessary to find out what registers are available (above mentioned control and status, but also address and other registers) and which bits represent which hardware functions.
Serial Communication
Synaser
It is very easy to build a serial communication software using the Synaser library. The example when used together with the Synaser documentation should be trivial to understand. The most important part is TBlockSerial.Config to configure the speed (in bits per second), data bits, parity bits, stop bits and handshake protocol, if any. The following code was tested with a serial mouse connected to COM 1.program comm;
{$apptype console}
uses
Classes, SysUtils, Synaser;
var
ser: TBlockSerial;
begin
ser:=TBlockSerial.Create;
try
ser.Connect('COM1');
ser.config(1200, 7, 'N', SB1, False, False);
while True do
Write(IntToHex(ser.RecvByte(10000), 2), ' ');
finally
ser.free;
end;
end.
The reason is not difficult to understand: The application is in the while true do - loop, which is, to be more precisely, an endless loop. There is no abort-condition, so the only way to close the application is to close the terminal or to press CTRL-C. But if you quit the application this way, the important part with "ser.free", which frees the serial port, will never be called. This problem is described in the following thread in the German Lazarus-Forum http://www.lazarusforum.de/viewtopic.php?f=10&t=2082
There is a bit code around the main application to make every user clear, not to press CTRL-C. If anyone is worrying, why /dev/ttyUSB0 is used for com-port: this is due to the USB to Serial Adapter (from Digitus) on the test-system. If you have an built-in serial port, please use the 'Com0' - declaration like in the code - example above.
program serialtest;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes,SysUtils,Synaser,Crt
{ you can add units after this };
var l:boolean;
function check_affirmation():boolean;
var k:string;
begin
Writeln('To quit the application please do NOT use CTRL-C! Instead, please press any key to quit the application! '+
'Please confirm this notification before the application continues! '+
'[0]=Quit, [1]=Confirm, please continue! ');
Writeln('Your decision: ');
Read(k);
if StrtoInt(k) = 1 then
begin
check_affirmation:=true;
Writeln('OK, application continues ...');
end
else
begin
check_affirmation:=false;
Writeln('Abort');
end
end;
procedure RS232_connect;
var
ser: TBlockSerial;
begin
ser:=TBlockSerial.Create;
try
ser.Connect('/dev/ttyUSB0'); //ComPort
Sleep(1000);
ser.config(1200, 7, 'N', SB1, False, False);
Write('Device: ' + ser.Device + ' Status: ' + ser.LastErrorDesc +' '+
Inttostr(ser.LastError));
Sleep(1000);
repeat
Write(IntToHex(ser.RecvByte(10000), 2), ' ');
until keypressed; //Important!!!
finally
Writeln('Serial Port will be freed...');
ser.free;
Writeln('Serial Port was freed successfully!');
end;
end;
begin
l:=check_affirmation();
if l=true then
RS232_connect()
else
Writeln('Program quit! ');
end.
It is also worth noting the function of the TBlockSerial.LinuxLock parameter under linux. When set to default of True, a connect will try to create a lock file (eg. "LCK..ttyUSB0") under /var/lock and fail if a lock already exists for the requested port. The lock file will be left over if Free was not called. Setting LinuxLock to False will make Synaser ignore port locking.
There are alternatives to Synaser; see below.
5dpo
There is also a visual component 5dpo that is based on Synaser.TLazSerial
Based on 5dpo (and therefore Synapse): http://forum.lazarus.freepascal.org/index.php/topic,20481.0.htmlFPC built in Serial unit
Another very simple fpc serial unit is now part of FreePascal (since version 2.2.2): just put Serial in your Uses list however there does not seem to be any documentation other than the Serial.pp source file and some discussions.A simple example using FPC 2.6.2 on WIN7.
Program TestSerialPortCom;
{
Usage options:
TestSerialPortCom => uses default COM1
TestSerialPortCom 8 'Hello' => uses COM8 and output 'Hello' to port before waiting for an answer
the program will open an serialport and output Hello, after that the code will wait unitil a CR (#13) is recieved
or a key is pressed.
}
uses
serial, crt;
VAR
serialhandle : LongInt;
ComPortName : String;
s,tmpstr,txt : String;
ComOut,ComIn : String;
ComPortNr : integer;
writecount : integer;
status : LongInt;
BitsPerSec : LongInt;
ByteSize : Integer;
Parity : TParityType; { TParityType = (NoneParity, OddParity, EvenParity); }
StopBits : Integer;
Flags : TSerialFlags; { TSerialFlags = set of (RtsCtsFlowControl); }
ErrorCode : Integer;
BEGIN
ComPortNr:=1;
tmpstr:='';
txt:='';
writeln('Parameters ',ParamCount);
if (ParamCount>0) then
begin
tmpstr:= ParamStr(1);
val(tmpstr,ComPortNr,ErrorCode);
if (ParamCount>1) then
begin
txt:= ParamStr(2);
{val(tmpstr,ComPortNr,ErrorCode);}
end;
end;
str(ComPortNr,tmpstr);
ComPortName:= 'COM'+tmpstr+':';
writeln('Using '+ComPortname);
serialhandle := SerOpen(ComPortName);
Flags:= [ ]; // None
SerSetParams(serialhandle,9600,8,NoneParity,1,Flags);
s:=txt; // use the input text
writeln('OUT '+s);
s:=s+#13+#10; { CR + LF }
writecount := length(s);
status := SerWrite(serialhandle, s[1], writecount );
// The next line is for debugging only!
writeln('status: ', status, ' writecount: ', writecount);
if status > 0 then
begin
writeln('Waiting for answer');
{ wait for an answer }
s:='';
ComIn:='';
while (Length(Comin)<10) and (status>=0) and not keypressed do begin
status:= SerRead(serialhandle, s[1], 10);
if (s[1]=#13) then status:=-1; { CR => end serial read }
if (status>0) then ComIn:=ComIn+s[1];
if (status>0) then begin
writeln(status,' ',length(ComIn),' ASCII ',ord(s[1]),' INP ',ComIn);
end;
end;
end
else
writeln('ERROR - Unable to send.');
SerSync(serialhandle); { flush out any remaining before closure }
SerFlushOutput(serialhandle); { discard any remaining output }
SerClose(serialhandle);
END.
Serial port names on Windows
COM ports are named with a number on Windows 9x-based OSes (95,98,ME), e.g. COM1, COM30.On Windows NT-based systems (NT, 2000, XP, Vista, Windows 7, Windows 8), COM ports are numbered too, but only for compatibility with DOS/Win9x.
Use this code to get the real name:
// ComNr is obviously the number of the COM port
if ComNr > 9 then
Result := Format('\\\\.\\COM%d', [ComNr])
else
Result := Format('COM%d', [ComNr]);
USB
libusb
A cross platform possibility for Linux, BSDs and Mac OS X is libusb.Headers are listed in http://www.freepascal.org/contrib/db.php3?category=Miscellaneous:
name | author | version | date | link | remarks |
---|---|---|---|---|---|
libusb.pp | Uwe Zimmermann | 0.1.12 | 2006-06-29 | http://www.sciencetronics.com/download/fpc_libusb.tgz |
|
libusb.pas | Johann Glaser | |
2012-09-23 | https://github.com/hansiglaser/pas-libusb | includes OOP wrapper, see branch "libusb-1.0" for libusb 1.0 |
fpcusb | Joe Jared | 0.11-14 | 2006-02-02 | http://relays.osirusoft.com/fpcusb.tgz | download link broken |
libusb.pp | Marko Medic | 1.0 | 2010-12-14 | http://www.lazarus.freepascal.org/index.php/topic,11435.0.html |
|
FTDI
If you use one of the chips from FTDI, you can use their pascal headers for their dll interface to the chips.Devices in general
On Windows, you can manage devices from code. Please see here: Windows_Programming_Tips#Enabling_and_disabling_devicesSee also
Subscribe to:
Posts (Atom)
Portugal Intel elevador da glória acidente
https://www.telegraph.co.uk/world-news/2025/09/04/several-injured-as-lisbons-gloria-funicular-derails/
