Coder Social home page Coder Social logo

hbjorgo / atlib Goto Github PK

View Code? Open in Web Editor NEW
48.0 3.0 20.0 374 KB

ATLib is a C# library that makes it easy to communicate with modems.

License: MIT License

C# 99.35% Smalltalk 0.19% PowerShell 0.47%
at atcommand atcommands sms gsm gsm-modem c-sharp hayes modem

atlib's Introduction

ATLib

CI Nuget Nuget

ATLib is a C# AT command library that abstracts away the commands and makes it easy to communicate with modems.

Hayes command set (commonly known as AT commands) is a command set frequently used in modems. Read more about it at Wikipedia.

Feedback is very much welcome and please request features 🙂

HeboTech.GsmApi is a REST API wrapping this library.

Supported commands:

  • Send SMS in PDU format (GSM 7 bit or UCS2 encoding)
  • Send concatenated SMS (message that spans over multiple SMSs) in PDU format (GSM 7 bit or UCS2 encoding)
  • SMS supports emojies
  • List SMSs
  • Read SMS (PDU format (GSM 7 bit or UCS2 encoding))
  • Delete SMS
  • Dial number
  • Answer incoming call
  • Hang up call
  • Get SIM status
  • Enter SIM PIN
  • Get remaining PIN & PUK attempts
  • Get product information
  • Get battery status
  • Get signal strength
  • Get / set date and time
  • Disable echo
  • Send USSD code
  • Get / set character set
  • Get IMSI
  • Some modems may also support modem specific commands

Events

  • Incoming call
  • Missed call
  • Call started
  • Call ended
  • SMS received
  • Error received
  • USSD response received
  • Generic event

Supported modems:

  • Adafruit FONA 3G (based on SIMCOM SIM5320 chipset)
  • D-Link DWM-222 (based on Qualcomm MDM9225 chipset)
  • TP-LINK MA260 (based on a Qualcomm chipset)
  • Cinterion MC55i
  • Other modems may work using one of the implementations above. You can add your own implementation using the existing functionality as base.

Other

  • Debug functionality that lets you intercept incoming and outgoing data

Usage

Install as NuGet package

dotnet add package HeboTech.ATLib

Using a serial port to communicate with a modem is easy:

// Set up serial port
using SerialPort serialPort = new SerialPort(args[0], 9600, Parity.None, 8, StopBits.One)
{
    Handshake = Handshake.RequestToSend
};
serialPort.Open();

// Create AT channel
using AtChannel atChannel = AtChannel.Create(serialPort.BaseStream);

// Create the modem
using IModem modem = new Fona3G(atChannel);

// Open AT channel
atChannel.Open();

// Configure modem with required settings before PIN
var requiredSettingsBeforePin = await modem.SetRequiredSettingsBeforePinAsync();

// Get SIM status
var simStatus = await modem.GetSimStatusAsync();
Console.WriteLine($"SIM Status: {simStatus}");

if (simStatus == SimStatus.SIM_PIN)
{
    var simPinStatus = await modem.EnterSimPinAsync(new PersonalIdentificationNumber("<PIN>"));
    Console.WriteLine($"SIM PIN Status: {simPinStatus}");
}

// Configure modem with required settings after PIN
var requiredSettingsAfterPin = await modem.SetRequiredSettingsAfterPinAsync();

// Send SMS to the specified number
var smsReference = await modem.SendSmsAsync(new PhoneNumber("123456789"), "Hello ATLib!");
Console.WriteLine($"SMS Reference: {smsReference}");

Because it relies on a stream, you can even control a modem over a network! Either use a network attached modem, or forward a modem serial port to a network port.

For more examples, check out the TestConsole project in the code.

atlib's People

Contributors

dogancoruh avatar hbjorgo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

atlib's Issues

International numbers

What about
Number = number.TrimStart('+');

In my case in Poland it doesn't work when plus is trimmed from phoneNumber.
It's ok when this line looks like this

Number = number;

BTW. it's great library, thanks for your work.

SIMCOM 7600 AT Commands

Hi
I have been developing a raspberry pi powered sensor. I am just adding the SIM7600G-H 4G HAT to the device. I started off using the standard serial ports but then came across your project and the implementation of pipes. I have taken a copy of the library and changed my code to run with the pipes. During the process I have added commands for the SIMCOM 7600 as well as some standard AT Commands. I have also added extra information to the SignalQuality including decibels. Also I am using UnitsNet for anything like decibels or voltages.

Is this something you would be interested in me providing a pull request for?

Supports for 4G commands

Hello,

Is it planned to add support for commands related to LTE? Like on/off, switch between 4G/3G/etc.

Wrong way to use Task

reader = Task.Factory.StartNew(() => ReadPipeAsync(pipe, cancellationTokenSource.Token), TaskCreationOptions.LongRunning);

readerTask = Task.Factory.StartNew(() => ReaderLoopAsync(cancellationTokenSource.Token), TaskCreationOptions.LongRunning);

Task.Factory.StartNew with flag LongRunning will create new Task and run in new Thread (not run in ThreadPool)
But you use async await without SynchronizationContext will make ReadPipeAsync run in ThreadPool after await if await another task run in different thread.

In current, it work ok (maybe not) because PipeReader.ReadAsync not in the case (depends on input stream).
It may not work in the future if the library changes or modifies the code or specific stream input, so please keep this in mind if you modify the code or update the library.

class CustomStream : MemoryStream
{
    public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
    {
        await Task.Delay(10, cancellationToken);
        return await base.ReadAsync(buffer, cancellationToken);
    }
}
class Program
{
    static async Task Main(string[] args)
    {
        Stream _stream = new CustomStream();
        AtReader atReader = new AtReader(_stream);
        atReader.Open();
        Console.ReadLine();
    }
}

image


Suggested
Install Nito.AsyncEx.Context

reader = Task.Factory.StartNew(
    () => AsyncContext.Run(() => ReadPipeAsync(pipe, cancellationTokenSource.Token)), 
    TaskCreationOptions.LongRunning
);

Stream WriteAsync Hang

Lib have a error hang Stream.Write async if COM can't write data, any way to fix it

this is code make problem

protected async Task WriteAsync(string text, CancellationToken cancellationToken = default)
        {
            
            Console.WriteLine($"write {text}");

            byte[] buffer = Encoding.UTF8.GetBytes(text);
            await stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken); //hang, can't stop
            Console.WriteLine($"flush {text}");
            await stream.FlushAsync(cancellationToken);
            Console.WriteLine($"write {text} ok");

        }

I run in another Task, can't hang by UI, can you check it

Gsm7 Default encoding not reflecting LF/CR properly

The encoding table (Gsm7) is not correctly accounting for LF/CR ( \n and \r ) and I suppose escape:

It should be:

{ Gsm7Extension.Default, "@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà" },

#43

Thanks for the library!

How to make compatible with other brands

I have Huawei and Wavecom M1306B. Do you have any idea how to set the library to make it work with those modems? Or you have generic custom settings to achieve that purpose?

UCS2 encoding schema for arabic sms messages

Dear, I have Huawei e303 modem and i already able to use this library to send sms with this device, but now i have a problem sending Arabic language sms, i searched about it and found that it is a coding schema issue, i can send Arabic sms by another method but not with this library.
my device can support ("GSM", "IRA", "UCS2") character sets
so could you please explain for me how to implement the UCS2 coding schema for sending such type of sms using this library
thank you in advance.

Multiline Responses

Does this library support parsing multi-line responses? I'm trying to retrieve GNSS info from a U-Blox SARA R5.

TX-->AT+UGGSA?

RX-->+UGGSA: 1,$GNGSA,A,1,18,29,28,,,,,,,,,,11.16,7.03,8.672C
RX-->$GNGSA,A,1,86,,,,,,,,,,,,11.16,7.03,8.67
2A
RX-->
RX-->OK

The response puts each GSA string on a new line, so using await modem.RawCommandWithResponseAsync("AT+UGGSA?","");, I'm only able to see the first line of the response.

Sms Receiving

Good Morning
Thank you for the wonderful code. Must have taken you some time to write all that.

I really want to use your library however I need to be able to receive sms and parse.

Do you foresee this feature being available soon?

Thanks again for your hard work
Rob

How can I send SMS with delivery report?

First, thank you for awesome lib.

My question is how can I send sms with the delivery report. Someone on internet said that we need to setup modem by send the 2 commands:
AT+CNMI=2,1,0,1,0
AT+CSMP=49,167,0,0

I tried, but not success.

Cannot send SMS with Telit xe910 modem in PDU mode using v7.0.0

Hi,
I could send SMS with Telit xe910 Terminal using ATLib v7.0.0-RC2 via "Text mode", but in latest release v7.0.0 there is no "Text mode" anymore. I tried to send SMS using PDU mode but either process fails with CMS 301 / CMS 304 errors or it pretends as if SMS is sent, giving a CMGS response with no error, but does not send any SMS.

I tried both GSM7 and UCS2 character set but neither first nor second set works. I would be glad if "Text mode" functionalty exists in new releases.
Kind Regards

Unhandled Exception

string line = response.Intermediates.First();

SIM Status: SIM_READY
Unhandled exception. System.InvalidOperationException: Sequence contains no elements
   at System.Linq.ThrowHelper.ThrowNoElementsException()
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at HeboTech.ATLib.Modems.Generic.ModemBase.SendSmsAsync(PhoneNumber phoneNumber, String message)
   at sendsms.Program.Main(String[] args) in /home/test/sendsms/Program.cs:line 45
   at sendsms.Program.<Main>(String[] args)

Telit soft reset and set to factory profile feature request

Hi,
we are evaluating your library to communicate with Telit xe910 famiy GSM terminals. Time to time we need to soft reset GSM terminal via ATZ and/or AT&Fxxx (Set To Factory Defined Configuration) commands since terminal may hang and can't turn back to normal status due to several reasons. I would be glad if Telit modules are added to supported modems and soft reset + set to factory defined configuration AT commands are added to supported AT commands
Kind Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.