I'm trying the Serialport package to send some AT commands to COM6
import qualified Data.ByteString.Char8 as B
import System.Hardware.Serialport
let port = "COM6" -- Windows
s <- openSerial port defaultSerialSettings { commSpeed = CS2400 }
send s $ B.pack "AT\r"
recv s 10 >>= print
closeSerial s
Does recv s 10 >>= print show me the result of the sent command?
I have tried a few AT commands and couldn't get results.
I'm sure that the openport has succeeded.
After this:
send s $ B.pack "AT\r"
I do get the "\r" as a result.
But when i try send s $ B.pack "AT+CGMI" I get nothing
I have tried to connect with Putty and it works.
Related
I'm running into an error of *** Exception: Network.Socket.sendBuf: invalid argument (Transport endpoint is not connected) when calling Network.Socket.ByteString.sendAll (hackage docs - sendall) from the socket server (to send to the socket client).
I'm not sure why I get this error? Seems I can only send the data one way?
I also run into the same error when using netcat, instead of the Haskell client:
echo 'test' | nc -N -U /tmp2/test2.soc
Output from client:
*Server Main> main
Hello, Haskell!2
"sent ping....."
Output from the server:
*Server> serv
"begin"
"Running daemon"
"begin2"
<socket: 13>
"Got message:"
"ping"
"Sending pong...."
*** Exception: Network.Socket.sendBuf: invalid argument (Transport endpoint is not connected)
Complete project: https://github.com/chrissound/UnixSocketPingPongHaskellTest
Full source code:
client:
{-# Language OverloadedStrings #-}
module Main where
import Network.Socket hiding (send)
import Network.Socket.ByteString as NBS
import Control.Concurrent
import Control.Monad
main :: IO ()
main = do
putStrLn "Hello, Haskell!2"
withSocketsDo $ do
soc <- socket AF_UNIX Stream 0
connect (soc) (SockAddrUnix "/tmp2/test2.soc")
forever $ do
send soc ("ping")
threadDelay $ 1 * 10^6
print "sent ping....."
threadDelay $ 1 * 10^6
msg <- NBS.recv soc 400000
print msg
print "got reply to ping...."
close soc
server:
{-# Language OverloadedStrings #-}
module Server where
import Network.Socket hiding (send)
import Network.Socket.ByteString as NBS
import Control.Concurrent
import Control.Monad
serv :: IO ()
serv = do
print "begin"
print "Running daemon"
soc <- socket AF_UNIX Stream 0
bind soc . SockAddrUnix $ "/tmp2/test2.soc"
listen soc maxListenQueue
accept soc >>= (\(x,y)-> do
print "begin2"
print x
print y
forever $ do
msg <- NBS.recv x 400000
print "Sending pong...."
NBS.sendAll soc "ppong"
print "alll done"
threadDelay $ 3 * 10^6
)
You are sending on the listening socket; you probably want to send on the accepted socket instead.
listen soc maxListenQueue
accept soc >>= (\(x,y)-> do
...
NBS.sendAll soc "ppong" -- should be sendAll x "ppong"
We have some code to send metrics to a SOCK_DGRAM where another daemon listens and aggregates/proxies these messages. Opening the socket looks like:
sock <- socket
(ai :: AddressInfo Inet Datagram UDP):_ <- getAddressInfo (Just "127.0.0.1") Nothing aiNumericHost
connect s (socketAddress ai) { port }
return sock
And at the moment we write to it like:
send sock payload mempty
I want to ensure the call above doesn't block for very long (or at the very least doesn't block indefinitely), but my understanding of unix sockets is not very deep and I'm having trouble understanding how exactly send blocks, looking at internals here and here.
There is a related question here that was helpful: When a non-blocking send() only transfers partial data, can we assume it would return EWOULDBLOCK the next call?
So my questions specifically are:
General socket question: I see in this implementation send is going to block (after busy-waiting) until there is room in the buffer. How exactly is this buffer related to the consumer? Does this mean send may block indefinitely if our listen-ing daemon is slow or stalls?
If I would rather abort and never block, do I need to make my own fork of System.Socket.Unsafe, or am I missing something?
I'm only concerned with linux here.
EDIT: Also, and what probably got me started with all of this is I find that when the metrics collector is not running, that every other of my send calls above throws a "connection refused" exception. So why that is, or whether it's normal is another question I have.
EDIT2: Here's a complete example illustrating the connection refused issue if anyone would like to help repro:
import Data.Functor
import System.Socket
import System.Socket.Family.Inet
repro :: IO ()
repro = do
let port = 6565
(s :: Socket Inet Datagram UDP) <- socket
(ai :: AddressInfo Inet Datagram UDP):_ <- getAddressInfo (Just "127.0.0.1") Nothing aiNumericHost
connect s (socketAddress ai) { port }
putStrLn "Starting send"
void $ send s "FOO" mempty
void $ send s "BAR" mempty
putStrLn "done"
I'm using socket-0.5.3.0.
EDIT3: this seems to be due to the connect call, somehow. (Testing on sockets latest):
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, NamedFieldPuns #-}
import Data.Functor
import System.Socket
import System.Socket.Protocol.UDP
import System.Socket.Type.Datagram
import System.Socket.Family.Inet
repro :: IO ()
repro = do
(s :: Socket Inet Datagram UDP) <- socket
-- Uncommenting raises eConnectionRefused, everytime:
-- connect s (SocketAddressInet inetLoopback 6565 :: SocketAddress Inet)
putStrLn "Starting send"
void $ sendTo s "FOO" mempty (SocketAddressInet inetLoopback 6565 :: SocketAddress Inet)
void $ sendTo s "BAR" mempty (SocketAddressInet inetLoopback 6565 :: SocketAddress Inet)
putStrLn "done"
As I understand it we should be able to use connect (at least the underlying syscall) to set the default send address. I haven't dug into the implementation of connect in the library yet.
I've opened this: https://github.com/lpeterse/haskell-socket/issues/55
This isn't a Haskell issue -- it's expected behavior on Linux when sending two UDP packets to a localhost port with no listening process. The following C program:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/udp.h>
int main()
{
int s = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in dstaddr = { AF_INET, htons(6565), {htonl(0x7f000001)} };
if (connect(s, (struct sockaddr*) &dstaddr, sizeof(dstaddr)))
perror("connect");
if (send(s, "FOO", 3, 0) == -1)
perror("first send");
if (send(s, "BAR", 3, 0) == -1)
perror("second send");
return 0;
}
will print second send: Connection refused, assuming nothing is listening on localhost port 6565.
If you do any one of the following -- (i) send to a non-local host, (ii) drop the connect call and replace the sends with sendtos, or (iii) send packets to a port with a process listening for UDP packets -- then you won't get the error.
The behavior is a little complex and not well documented anywhere, though the manpages for udp(7) hint at it.
You may find the discussion in this Stack Overflow question helpful.
I am currently attempting to play audio files in Haskell using OpenAl. In order to do so, I am trying to get the example code at the ALUT git repository (https://github.com/haskell-openal/ALUT/blob/master/examples/Basic/PlayFile.hs) to work. However, it refuses to produce any sound. What am I missing here?
{-
PlayFile.hs (adapted from playfile.c in freealut)
Copyright (c) Sven Panne 2005-2016
This file is part of the ALUT package & distributed under a BSD-style license.
See the file LICENSE.
-}
import Control.Monad ( when, unless )
import Data.List ( intersperse )
import Sound.ALUT
import System.Exit ( exitFailure )
import System.IO ( hPutStrLn, stderr )
-- This program loads and plays a variety of files.
playFile :: FilePath -> IO ()
playFile fileName = do
-- Create an AL buffer from the given sound file.
buf <- createBuffer (File fileName)
-- Generate a single source, attach the buffer to it and start playing.
source <- genObjectName
buffer source $= Just buf
play [source]
-- Normally nothing should go wrong above, but one never knows...
errs <- get alErrors
unless (null errs) $ do
hPutStrLn stderr (concat (intersperse "," [ d | ALError _ d <- errs ]))
exitFailure
-- Check every 0.1 seconds if the sound is still playing.
let waitWhilePlaying = do
sleep 0.1
state <- get (sourceState source)
when (state == Playing) $
waitWhilePlaying
waitWhilePlaying
main :: IO ()
main = do
-- Initialise ALUT and eat any ALUT-specific commandline flags.
withProgNameAndArgs runALUT $ \progName args -> do
-- Check for correct usage.
unless (length args == 1) $ do
hPutStrLn stderr ("usage: " ++ progName ++ " <fileName>")
exitFailure
-- If everything is OK, play the sound file and exit when finished.
playFile (head args)
Unfortunately, while I don't get any errors, I also can\t hear any sound. Pavucontrol also does not seem to detect anything (no extra streams appear under the Playback tab).
Their HelloWorld example on the same git repository also gave neither errors nor sound.
I also tried the OpenALInfo function on the same git repository (https://github.com/haskell-openal/ALUT/blob/master/examples/Basic/OpenALInfo.hs), which further proves that I'm actually connecting to OpenAL, and gives some information about the versions which may or may not be useful:
ALC version: 1.1
ALC extensions:
ALC_ENUMERATE_ALL_EXT, ALC_ENUMERATION_EXT, ALC_EXT_CAPTURE,
ALC_EXT_DEDICATED, ALC_EXT_disconnect, ALC_EXT_EFX,
ALC_EXT_thread_local_context, ALC_SOFTX_device_clock,
ALC_SOFT_HRTF, ALC_SOFT_loopback, ALC_SOFT_pause_device
AL version: 1.1 ALSOFT 1.17.2
AL renderer: OpenAL Soft
AL vendor: OpenAL Community
AL extensions:
AL_EXT_ALAW, AL_EXT_BFORMAT, AL_EXT_DOUBLE,
AL_EXT_EXPONENT_DISTANCE, AL_EXT_FLOAT32, AL_EXT_IMA4,
AL_EXT_LINEAR_DISTANCE, AL_EXT_MCFORMATS, AL_EXT_MULAW,
AL_EXT_MULAW_BFORMAT, AL_EXT_MULAW_MCFORMATS, AL_EXT_OFFSET,
AL_EXT_source_distance_model, AL_LOKI_quadriphonic,
AL_SOFT_block_alignment, AL_SOFT_buffer_samples,
AL_SOFT_buffer_sub_data, AL_SOFT_deferred_updates,
AL_SOFT_direct_channels, AL_SOFT_loop_points, AL_SOFT_MSADPCM,
AL_SOFT_source_latency, AL_SOFT_source_length
Well, it turns out I posted here a bit too quickly. There was no problem with my code, but rather with my OpenAl settings. By adding
drivers=pulse,alsa
to /etc/openal/alsoft.conf OpenAl works. This is described in https://wiki.archlinux.org/index.php/PulseAudio#OpenAL.
I would like to stream stdin over an HTTP connection using text/event-stream. The Network.Wai.EventSource thing looks like a good candidate.
I tried using this code:
import Network.Wai
import Network.Wai.EventSource
import Network.Wai.Middleware.AddHeaders
import Network.Wai.Handler.Warp (run)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as C
import Blaze.ByteString.Builder.ByteString
toEvent :: [L.ByteString] -> ServerEvent
toEvent s = ServerEvent {
eventName = Nothing,
eventId = Nothing,
eventData = map fromLazyByteString s
}
createWaiApp :: IO L.ByteString -> Application
createWaiApp input = eventSourceAppIO $ fmap (toEvent . C.lines) input
main :: IO ()
main = run 1337 $ createWaiApp L.getContents
Which (I think) does:
Reads stdin as a Lazy ByteStream
Splits the ByteStream into lines
Produces one ServerEvent for all the lines (this feels wrong - there should presumably be multiple events?)
Builds a WAI Application from the IO ServerEvent
Binds the Application to port 1337
When I run this (e.g. using ping -c 5 example.com | stack exec test-exe) it doesn't respond until the whole of stdin has been read.
How do I build a Wai application that flushes out the HTTP connection every time it reads a line from stdin?
L.getContents is a single IO action, so only one event will be created.
Here is an example of eventSourcEventAppIO where multiple events are created:
import Blaze.ByteString.Builder.Char8 (fromString)
...same imports as above...
nextEvent :: IO ServerEvent
nextEvent = do
s <- getLine
let event = if s == ""
then CloseEvent
else ServerEvent
{ eventName = Nothing
, eventId = Nothing
, eventData = [ fromString s ]
}
case event of
CloseEvent -> putStrLn "<close event>"
ServerEvent _ _ _ -> putStrLn "<server event>"
return event
main :: IO ()
main = run 1337 $ eventSourceAppIO nextEvent
To test, in one window start up the server and in another run the command curl -v http://localhost:1337. For each line you enter in the server window you will get a data frame from curl. Entering a blank line will close the HTTP connection but the server will remain running allowing you to connect to it again.
I'm using the GHC API to parse a module. If the module contains syntax errors the GHC API writes them to stdout. This interferes with my program, which has another way to report errors. Example session:
$ prog ../stack/src/Stack/Package.hs
../stack/src/Stack/Package.hs:669:0:
error: missing binary operator before token "("
#if MIN_VERSION_Cabal(1, 22, 0)
^
../stack/src/Stack/Package.hs:783:0:
error: missing binary operator before token "("
#if MIN_VERSION_Cabal(1, 22, 0)
^
../stack/src/Stack/Package.hs
error: 1:1 argon: phase `C pre-processor' failed (exitcode = 1)
Only the last one should be outputted. How can I make sure the GHC API does not output anything? I'd like to avoid libraries like silently which solve the problem by redirecting stdout to a temporary file.
I already tried to use GHC.defaultErrorHandler, but while I can catch the exception, GHC API still writes to stdout. Relevant code:
-- | Parse a module with specific instructions for the C pre-processor.
parseModuleWithCpp :: CppOptions
-> FilePath
-> IO (Either (Span, String) LModule)
parseModuleWithCpp cppOptions file =
GHC.defaultErrorHandler GHC.defaultFatalMessager (GHC.FlushOut $ return ()) $
GHC.runGhc (Just libdir) $ do
dflags <- initDynFlags file
let useCpp = GHC.xopt GHC.Opt_Cpp dflags
fileContents <-
if useCpp
then getPreprocessedSrcDirect cppOptions file
else GHC.liftIO $ readFile file
return $
case parseFile dflags file fileContents of
GHC.PFailed ss m -> Left (srcSpanToSpan ss, GHC.showSDoc dflags m)
GHC.POk _ pmod -> Right pmod
Moreover, with this approach I cannot catch the error message (I just get ExitFailure). Removing the line with GHC.defaultErrorHandler gives me the output shown above.
Many thanks to #adamse for pointing me in the right direction! I have found the answer in Hint's code.
It suffices to override logging in the dynamic flags:
initDynFlags :: GHC.GhcMonad m => FilePath -> m GHC.DynFlags
initDynFlags file = do
dflags0 <- GHC.getSessionDynFlags
src_opts <- GHC.liftIO $ GHC.getOptionsFromFile dflags0 file
(dflags1, _, _) <- GHC.parseDynamicFilePragma dflags0 src_opts
let dflags2 = dflags1 { GHC.log_action = customLogAction }
void $ GHC.setSessionDynFlags dflags2
return dflags2
customLogAction :: GHC.LogAction
customLogAction dflags severity _ _ msg =
case severity of
GHC.SevFatal -> fail $ GHC.showSDoc dflags msg
_ -> return () -- do nothing in the other cases (debug, info, etc.)
The default implementation of GHC.log_action can be found here:
http://haddock.stackage.org/lts-3.10/ghc-7.10.2/src/DynFlags.html#defaultLogAction
The code for parsing remains the same in my question, after having removed the line about GHC.defaultErrorHandler, which is no longer needed, assuming one catches exceptions himself.
I have seen this question before and then the answer was to temporarily redirect stdout and stderr.
To redirect stdout to a file as an example:
import GHC.IO.Handle
import System.IO
main = do file <- openFile "stdout" WriteMode
stdout' <- hDuplicate stdout -- you might want to keep track
-- of the original stdout
hDuplicateTo file stdout -- makes the second Handle a
-- duplicate of the first
putStrLn "hi"
hClose file