class SmsHandler: def __init__(self, serial_port, baudrate): self.connection = Modem(serial_port, baudrate) def send_sms(self, params={}): """ Sends the sms in the PDU mode Errors range: 3x :param params: json {phone:"", text: ""} :return: """ if not params.get('phone'): raise AppException("phone number is required", 30) if not Validator.check_phone(params.get('phone')): raise AppException("phone number has invalid format [%s]" % params.get('phone'), 31) if not params.get('text'): raise AppException("payload is required", 32) Validator.check_text(params.get('text')) result = self.connection.send_sms_pdu(str(params.get('phone')), params.get('text')) if not result: raise AppException("internal modem error. The message not sended", 33) log = logging.getLogger(logger.NAME) log.info("Sms successfully send") return "success" def get_balance(self, params={}): """ Request balance and parses response Errors range: 4x :param params: void :return: """ result = self.connection.check_balance() if not result: raise AppException("internal modem error. Balance does not received", 40) log = logging.getLogger(logger.NAME) log.info("Balance successfully received [%s]" % result) return result def nothing(self, params={}): """ dummy Errors range: 1x :param params: void :return: """ raise AppException("command is required", 10)
def __init__(self): self.p = pyaudio.PyAudio() self.fs = 44100 self.duration = 0.03 self.f = 300.0 self.stream = self.p.open(format=self.p.get_format_from_width(4), channels=1, rate=self.fs, output=True) self.modem = Modem()
def test_channel_estimation(self): ch = Channel() ch.impulse_response = ch.test_impulse_response # use modem to generate frame modem = Modem(get_ofdm_preamble_based()) p = modem.param tx_frame = modem.transmitter() rx_frame = ch.multipath(tx_frame) ch_estimator = ChannelEstimation() estimated_channel = ch_estimator.estimate_channel_form_preamble( rx_frame[p.Ncp + np.arange(p.Npreamble)], p.halfpreamble) estimated_impulse_response = np.fft.ifft(estimated_channel) np.testing.assert_array_almost_equal( ch.last_impulse_response, estimated_impulse_response[:len(ch.last_impulse_response)], decimal=2)
def test_channel_equalizer(self): ch = Channel() ch.impulse_response = ch.test_impulse_response modem = Modem(get_ofdm_preamble_based()) p = modem.param tx_frame = modem.transmitter() rx_frame = ch.multipath(tx_frame) idx = p.Ncp + p.Npreamble_cp_cs + np.arange(p.Npayload) tx_payload = tx_frame[idx] rx_payload = rx_frame[idx] ch_estimator = ChannelEstimation() estimated_channel = ch_estimator.estimate_channel_form_preamble( rx_frame[p.Ncp + np.arange(p.Npreamble)], p.halfpreamble) equalizer = Equalizer() eq_payload = np.fft.ifft( equalizer.equalize(np.fft.fft(rx_payload), estimated_channel)) np.testing.assert_array_almost_equal(tx_payload, eq_payload, decimal=1)
def test(args): from modem import Modem # TODO: decouple CallAttendant from modem modem = Modem(None) messenger = Messenger(None, modem) return 0
def execute_options(): parser = argparse.ArgumentParser( description="""This is SMS Modem Python""") parser.add_argument('-s', '--sms', nargs=2, help='Send sms <With text> to <Phone_number>', metavar=('SMS_Text', 'Phone_Number')) parser.add_argument('-c', '--call', nargs=1, help='Calling number xxx', metavar='Phone_Number') args = parser.parse_args() if args.sms is not None: modem = Modem() devices = modem.devices pool = ThreadPool(16) f = partial(sms_function, *args.sms) result = pool.map(f, devices) # # close the pool and wait for the work to finish pool.close() pool.join() _file = Utils(constant.SMS_FILE) for iterator in result: (port, phone_number, sms) = iterator try: _file.write_sms_to_file(port, phone_number.decode(), sms) except: print('No number') elif args.call is not None: modem = Modem() devices = modem.devices for iterator in devices: ser = Ser(iterator) ser.call(*args.call) else: sys.exit(2)
def __init__(self): self.mic = Mic() self.speaker = Speaker() self.client = Client() self.modem = Modem() self.selectedMod = 'AM' self.modulations = { 'AM': self.modem.modAm, 'AMSC': self.modem.modAmsc, 'FM': self.modem.modFm } self.demodulations = { 'AM': self.modem.demodAm, 'AMSC': self.modem.demodAmsc, 'FM': self.modem.demodFm } self.fig, self.axes = plt.subplots(4, 1, figsize=[6,8]) plt.subplots_adjust(top=0.7) for i in range(4): self.axes[i].axes.xaxis.set_visible(False) self.axes[i].axes.yaxis.set_visible(False) self.input_ip = TextBox(plt.axes([0.1, 0.05, 0.4, 0.05]), '', initial='192.168.0.20') self.btn_connect = Button(plt.axes([0.5, 0.05, 0.2, 0.05]), 'Connect') self.btn_disconnect = Button(plt.axes([0.7, 0.05, 0.2, 0.05]), 'Disconnect') self.btn_am = Button(plt.axes([0.1, 0.94, 0.2, 0.05]), 'AM') self.btn_amsc = Button(plt.axes([0.3, 0.94, 0.2, 0.05]), 'AMSC') self.btn_fm = Button(plt.axes([0.5, 0.94, 0.2, 0.05]), 'FM') self.sld_cutoff = Slider(plt.axes([0.1, 0.91, 0.7, 0.02]), 'Cutoff', 1., 2000., valinit=1000, valstep=1.) self.sld_order = Slider(plt.axes([0.1, 0.87, 0.7, 0.02]), 'Order', 2, 50, valinit=5, valstep=1) self.sld_fm_carrier = Slider(plt.axes([0.1, 0.83, 0.7, 0.02]), 'FM Freq', 3000., 20000., valinit=10000., valstep=100.) self.sld_fm_devsiat = Slider(plt.axes([0.1, 0.79, 0.7, 0.02]), 'FM Desv', 300., 4000., valinit=1000., valstep=10.) self.sld_am_carrier = Slider(plt.axes([0.1, 0.75, 0.7, 0.02]), 'AM Freq', 3000., 20000., valinit=3000., valstep=100.) self.btn_am.on_clicked(self.selectAM) self.btn_amsc.on_clicked(self.selectAMSC) self.btn_fm.on_clicked(self.selectFM) self.btn_connect.on_clicked(self.connect) self.btn_disconnect.on_clicked(self.disconnect) self.sld_cutoff.on_changed(self.changeCutoff) self.sld_order.on_changed(self.changeOrder) self.sld_fm_carrier.on_changed(self.changeFmCarrier) self.sld_fm_devsiat.on_changed(self.changeFmDevsiat) self.sld_am_carrier.on_changed(self.changeAmCarrier) plt.show()
def send_backend_data(sim: ubirch.SimProtocol, modem: Modem, conn: Connection, api_function, uuid, data) -> (int, bytes): MAX_MODEM_RESETS = 1 # number of retries with modem reset before giving up MAX_RECONNECTS = 1 # number of retries with reconnect before trying a modem reset for reset_attempts in range(MAX_MODEM_RESETS + 1): # check if this is a retry for reset_attempts if reset_attempts > 0: print("\tretrying with modem reset") sim.deinit() modem.reset( ) # TODO: should probably be connection.reset_hardware() conn.connect() # try to send multiple times (with reconnect) try: for send_attempts in range(MAX_RECONNECTS + 1): # check if this is a retry for send_attempts if send_attempts > 0: print("\tretrying with disconnect/reconnect") conn.disconnect() conn.connect() try: print("\tsending...") return api_function(uuid, data) except Exception as e: # TODO: log/print exception? print("\tsending failed: {}".format(e)) # (continues to top of send_attempts loop) else: # all send attempts used up raise Exception("all send attempts failed") except Exception as e: print(repr(e)) # (continues to top of reset_attempts loop) else: # all modem resets used up raise Exception("could not establish connection to backend")
class GradientFunc: def __init__(self): self.p = pyaudio.PyAudio() self.fs = 44100 self.duration = 0.03 self.f = 300.0 self.stream = self.p.open(format=self.p.get_format_from_width(4), channels=1, rate=self.fs, output=True) self.modem = Modem() def __del__(self): self.stream.stop_stream() self.stream.close() self.p.terminate() @staticmethod def generate_tone(fs, freq, duration): npsin = np.sin(2 * np.pi * np.arange(fs * duration) * freq / fs) samples = npsin.astype(np.float32) return 0.1 * samples def __call__(self, gradient): """ # play gradients norm_grad = np.linalg.norm(gradient) tone = self.f + (norm_grad * 500.0) samples = self.generate_tone(self.fs, tone, self.duration).astype(np.float32) """ audio_out = self.modem.convert_data_to_audio(gradient.flatten()) decoded_gradients = self.modem.convert_audio_to_floats(audio_out) # if you want to regret being alive, # self.stream.write(audio_out.tobytes()) return decoded_gradients.reshape(gradient.shape)
def __init__(self, hostname="127.0.0.1", port=7362, reset=True, log=False): self.logger = logging.getLogger("pyfldigi.Client") self.ip_address = hostname self.port = port self.logger.debug( "Attempting to connect to connect to fldigi at IP address={}, port={}, via XMP-RPC" .format(self.ip_address, self.port)) self.client = xmlrpc.client.ServerProxy( "http://{}:{}/".format(self.ip_address, self.port), transport=RequestsTransport(use_builtin_types=True), allow_none=True, ) self.main = Main(clientObj=self) self.modem = Modem(clientObj=self) self.rig = Rig(clientObj=self) self.log = Log(clientObj=self) self.text = Text(clientObj=self) self.spot = Spot(clientObj=self) self.flmsg = Flmsg(clientObj=self) self.io = Io(clientObj=self) self.txmonitor = TxMonitor(clientObj=self) # do this last
def main(): # modem = Modem(get_ofdm_preamble_based()) modem = Modem(get_gfdm_preamble_based()) session = Session(modem) session.run()
length = bytearray([len(op) + 1]) return prefix + length + op + bytearray([crc]) if __name__ == '__main__': import sys, os logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) from link import Link from modem import Modem serial = os.environ.get('SERIAL') msg = fmt_command(commands.ReadPumpModel(serial=serial), serial=serial) print lib.hexdump(msg) # sys.exit(0) link = Link.Make() # print link.device with link: modem = Modem(link) print modem modem.init_modem() with modem.remote() as control: # now in remote command mode. remote = Remote(link, serial) model = remote.query(commands.ReadPumpModel) print model print "MODEL", model.getData() # end remote command mode
import signal import threading # Application imports sys.path.append("../modules") from config import Config from modem import Modem from logger import log from queue import Queue from parse import Parse # Global variables QDIR = "moqueue" # Instantiate objects App = Modem() Parser = Parse() Q = Queue(QDIR) # Callback is fired when an SBD message comes in. def _callback(data): print("Callback: %s" % data) message_response = Config.get("respond")["response"] string_to_match = Config.get("respond")["match"] if string_to_match in data: Q.add(message_response) old = os.stat(QDIR).st_mtime
length = bytearray([len(op) + 1]) return prefix + length + op + bytearray([crc]) if __name__ == '__main__': import sys, os logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) from link import Link from modem import Modem serial = os.environ.get('SERIAL') msg = fmt_command(commands.ReadPumpModel(serial=serial), serial=serial) print lib.hexdump(msg) # sys.exit(0) link = Link.Make( ) # print link.device with link: modem = Modem(link) print modem modem.init_modem( ) with modem.remote( ) as control: # now in remote command mode. remote = Remote(link, serial) model = remote.query(commands.ReadPumpModel) print model print "MODEL", model.getData( ) # end remote command mode
from modem import Modem import time modem = Modem() inp=1 while 1 : # get keyboard input inp = input() if inp == 'exit': modem.close() exit() else: modem.send_AT_command(inp) print(modem.get_response()) print(modem.get_response()) print(modem.get_response())
def test_ofdm_b_1(self): p = get_ofdm_preamble_based() m = Modem(p) self._test_modem(m)
else: print("\tno SD card found") # set up error handling max_file_size_kb = 10240 if SD_CARD_MOUNTED else 20 error_handler = ErrorHandler(file_logging_enabled=True, max_file_size_kb=max_file_size_kb, sd_card=SD_CARD_MOUNTED) try: # get system information print("pycom firmware: ", uname()) # print("modem firmware: ", sqnsupgrade.info()) # initialize modem lte = LTE() modem = Modem(lte, error_handler) try: # reset modem on any non-normal loop (modem might be in a strange state) if not COMING_FROM_DEEPSLEEP: print("++ not coming from sleep, resetting modem") modem.reset() print("++ getting IMSI") imsi = modem.get_imsi() print("IMSI: " + imsi) except Exception as e: print("\tERROR setting up modem") error_handler.log(e, COLOR_MODEM_FAIL) while True: machine.idle()
action="store_true", dest="verbose", default=False, help="Print informative messages to the command line.") (options, args) = opt_parser.parse_args() # Do something with the returned message! def _callback(value): print(value) # Instantiate classes Q = Queue(QDIR) App = Modem() # If there is an argument add it to the queue and start a monitoring thread if len(args) < 1: sys.stderr.write( "Please add a message to send.\nUsage: ./reply.py <message>\n") sys.exit(1) else: Q.add(args[0]) # Monitor the queue dir if there are files send them oldest to newest. def check_queue_dir(dir): while True: while Q.count() > 0:
def test_ofdm_b_1_pilot(self): p = get_ofdm_pilot_based() p.B = 1 m = Modem(p) self._test_modem(m)
def __init__(self, serial_port, baudrate): self.connection = Modem(serial_port, baudrate)
from mic import Mic from speaker import Speaker from modem import Modem mic = Mic() speaker = Speaker() modem = Modem() while True: entrada = mic.read() # modulado = modem.modAm(entrada) # demodulado = modem.demodAm(modulado) modulado = modem.modAmsc(entrada) demodulado = modem.demodAmsc(modulado) # modulado = modem.modFm(entrada) # demodulado = modem.demodFm(modulado) speaker.play(demodulado)
# mount SD card if there is one print("++ mounting SD") SD_CARD_MOUNTED = mount_sd() if SD_CARD_MOUNTED: print("\tSD card mounted") else: print("\tno SD card found") # set up error handling max_file_size_kb = 10240 if SD_CARD_MOUNTED else 20 error_handler = ErrorHandler(file_logging_enabled=True, max_file_size_kb=max_file_size_kb, sd_card=SD_CARD_MOUNTED) try: # initialize modem lte = LTE() modem = Modem(lte, error_handler) try: # reset modem on any non-normal loop (modem might be in a strange state) if not COMING_FROM_DEEPSLEEP: print("++ not coming from sleep, resetting modem") modem.reset() print("++ getting IMSI") imsi = modem.get_imsi() print("IMSI: " + imsi) except Exception as e: print("\tERROR setting up modem") error_handler.log(e, COLOR_MODEM_FAIL) while True: machine.idle()
import time from modem import quit, Modem try: modem = Modem("/dev/bandrich.control") #test that modem is there print "INFO: check modem's presence" modem.send('AT') r = modem.wait() if r.ret != True and "NO CARRIER" not in r.data: print "ERROR: no modem?" quit(1) if "NO CARRIER" in r.data: print "WARNING: 'NO CARRIER' detected, not sure if handled correctly" #deactivate the modem print "INFO: deactivate the modem" modem.send('AT+CFUN=4') if modem.wait().ret != True: print "ERROR: failed asking modem for deactivation" quit(1) except BaseException, e: print "ERROR: " + str(e) quit(1) quit(0)
import time from modem import quit, Modem try: modem = Modem("/dev/bandrich.control") #test that modem is there print "INFO: check modem's presence" modem.send('AT') if modem.wait().ret != True: print "ERROR: no modem?" quit(1) #activate the modem, be brutal and reset it too! print "INFO: reset and activate the modem" modem.send('AT+CFUN=1,1') if modem.wait().ret != True: print "ERROR: failed asking modem for activation" quit(1) #modem has gone! wait for it to pop up again modem.modem_reset_cycle() #wait for modem to be connected #timeout after one minute print "INFO: wait for modem to be connected (timeout: one minute)" start_time = time.time() while True: modem.send('AT+CGATT?') r = modem.wait()
def test_ofdm_b_2(self): p = get_ofdm_preamble_based() p.B = 2 m = Modem(p) self._test_modem(m)
import time from modem import quit, Modem try: modem = Modem("/dev/ttyUSB0") #test that modem is there print "INFO: check modem's presence" modem.send('AT') r = modem.wait() if r.ret != True and "NO CARRIER" not in r.data: print "ERROR: no modem?" quit(1) if "NO CARRIER" in r.data: print "WARNING: 'NO CARRIER' detected, not sure if handled correctly" #deactivate the modem print "INFO: deactivate the modem" modem.send('AT+CFUN=0') if modem.wait().ret != True: print "ERROR: failed asking modem for deactivation" quit(1) except BaseException, e: print "ERROR: " + str(e) quit(1) quit(0)
from __main__ import app from flask import request, jsonify from modem import Modem from sms import SMS, SMS_factory modem = Modem() @app.route('/modem/send_command', methods=['POST']) def send_command(): command = request.json.get('command', None) modem.send_AT_command(command) response = modem.get_response() return response, 200 @app.route('/modem/sms/all', methods=['GET']) def get_all_sms(): modem.send_AT_command('AT+CMGL="ALL"') response = modem.get_response() sms_list = list() if response.strip() == 'ERROR': return jsonify(message = "ERROR"), 503 else: sms_list = SMS_factory(response).sms_list return jsonify([s.serialize() for s in sms_list]), 200 @app.route('/modem/sms/<id>', methods=['GET']) def get_sms(id): modem.send_AT_command(f'AT+CMGR={id}') response = modem.get_response() if response.strip() == 'ERROR': return jsonify(message = "ERROR"), 503
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from modem import Modem import sched import sqlite3 import datetime import sys m = Modem("192.168.100.1") conn = sqlite3.connect('modem_stats.db') def signal_handler(signal, frame): conn.close() sys.exit(0) def create_db(): c = conn.cursor() c.execute('''DROP TABLE IF EXISTS stats''') c.execute( '''CREATE TABLE stats (time text, dstream_pwr text, dstream_snr text, ustream_pwr text)''' ) conn.commit()
import sys from modem import Modem from modem import CommandError import modemdefs as ModemDefs import time devEui = "0000000000000000" # TODO appEui = "0000000000000000" # TODO appKey = "00000000000000000000000000000000" # TODO # serialPort = '/dev/ttyUSB0' # Linux serialPort = '/dev/tty.usbserial-M1V6V7' # MacOS: $ ls /dev/tty.u* try: print("Setup...") m = Modem(serialPort) m.deveui = bytes(bytearray.fromhex(devEui)) m.joineui = bytes(bytearray.fromhex(appEui)) m.setnwkkey(bytes(bytearray.fromhex(appKey))) loraPort = 1 # valid values are 1 to 224 loraPayload = b'hello' print("Joining...") m.join() event = None while (event == None) or (event.type != ModemDefs.EVT_JOINED): event = m.getevent() print("Joined :)") while True: try: