diff --git a/lib/biju/pdu.rb b/lib/biju/pdu.rb index 741b2df..001b605 100644 --- a/lib/biju/pdu.rb +++ b/lib/biju/pdu.rb @@ -1,9 +1,11 @@ require 'biju/pdu/gsm7bit' +require 'biju/pdu/ucs2' module Biju module PDU ENCODING = { gsm7bit: GSM7Bit, + ucs2: UCS2, } def self.encode(hash) @@ -30,7 +32,8 @@ module Biju '%S%M%H%d%m%y%Z'), user_data_length: string[52..53], } - res[:sender_number] = string[22..(22 + res[:address_length])] + res[:sender_number] = string[22..(22 + res[:address_length])].scan(/../) + .map(&:reverse).join.chop res[:user_data] = PDU.decode_user_data(string[54..-1], encoding: res[:data_coding_scheme], length: res[:user_data_length].hex) @@ -41,8 +44,8 @@ module Biju def self.decode_user_data(message, encoding: '00', length: 0) encoding = data_coding_scheme(encoding) unless encoding.is_a?(Symbol) - raise ArgumentError, "Unknown encoding" unless ENCODING.has_key?(:gsm7bit) - ENCODING[:gsm7bit].decode(message, length: length) + raise ArgumentError, "Unknown encoding" unless ENCODING.has_key?(encoding) + ENCODING[encoding].decode(message, length: length) end def self.data_coding_scheme(dcs) diff --git a/lib/biju/pdu/ucs2.rb b/lib/biju/pdu/ucs2.rb new file mode 100644 index 0000000..a7f5fd8 --- /dev/null +++ b/lib/biju/pdu/ucs2.rb @@ -0,0 +1,14 @@ +module Biju + module PDU + class UCS2 + def self.decode(string, length: 0) + string.scan(/.{4}/).map { |char| char.hex.chr('UCS-2BE') }.join + .encode('UTF-8', 'UCS-2BE') + end + + def self.encode(string) + string.encode('UCS-2BE').chars.map { |char| "%04x" % char.ord }.join + end + end + end +end diff --git a/spec/biju/pdu/ucs2_spec.rb b/spec/biju/pdu/ucs2_spec.rb new file mode 100644 index 0000000..aa696a0 --- /dev/null +++ b/spec/biju/pdu/ucs2_spec.rb @@ -0,0 +1,30 @@ +require 'spec_helper' +require 'biju/pdu/ucs2' + +describe Biju::PDU::UCS2 do + describe '::decode' do + it "decodes string" do + expect(Biju::PDU::UCS2.decode('00C700E700E200E300E500E4016B00F80153', length: 4)).to eq('Ççâãåäūøœ') + end + end + + describe '::encode' do + it "encodes string" do + expect(Biju::PDU::UCS2.encode('Ççâãåäūøœ').upcase).to eq('00C700E700E200E300E500E4016B00F80153') + end + end + + it "gives same text after encoding and decoding" do + strings = [ + 'My first TEST', + '{More çomplicated]', + 'And on€ More~', + 'þß®', + ] + + strings.each do |string| + expect(Biju::PDU::UCS2.decode( + Biju::PDU::UCS2.encode(string), length: string.length)).to eq(string) + end + end +end